Swift 3中如何创建UILabel数组?代码报错求助
Hey there! Let's sort out that issue with creating a UILabel array. The problem in your original code is a type mismatch: you declared label as a single UILabel instance, but tried to assign an array of UILabels to it. That's why the compiler throws an error.
Here's how to fix it properly:
Step 1: Correctly Declare the Array Variable
First, make sure your variable is typed as an array of UILabels ([UILabel]) instead of a single UILabel. Then you can assign your existing labels to it.
Example with Pre-Existing Labels
If you already have label1, label2, label3 created:
// Assume these are your pre-configured UILabels let label1 = UILabel() let label2 = UILabel() let label3 = UILabel() // Declare and initialize the UILabel array correctly var labels: [UILabel] = [label1, label2, label3] // Now you can work with the array, e.g., batch update properties for label in labels { label.text = "Updated Text" label.textColor = .darkGray label.font = UIFont.systemFont(ofSize: 14) }
Example: Create and Initialize the Array in One Go
If you haven't created the labels yet, you can initialize the array with new UILabel instances directly:
// Create an array of UILabels with frames and initial properties var labels: [UILabel] = [ UILabel(frame: CGRect(x: 20, y: 50, width: 300, height: 40)), UILabel(frame: CGRect(x: 20, y: 100, width: 300, height: 40)), UILabel(frame: CGRect(x: 20, y: 150, width: 300, height: 40)) ] // Use forEach to apply settings to all labels labels.forEach { label in label.textAlignment = .center label.backgroundColor = .lightGray label.text = "I'm part of the array!" }
Key Takeaway
The critical fix is changing the variable type from UILabel to [UILabel]—this tells Swift you're working with a collection of UILabel instances instead of a single one.
内容的提问来源于stack exchange,提问作者user3702475

