P.aishly
P.aishly

Reputation: 31

Create UILabel dynamically and Change the text Also

I am trying to create 7 UILabel programmatically and I am not able to change the text of all UILabel.

let viewsCount = 2
let viewLblcount   =   7
var messageForLbl = ["helo", "bhago", "futo", "bhensali" , "bhaaw bhaaw", "haha" ,"alladh"]

let floatValue = CGFloat(viewsCount)
let floatLbl = CGFloat(viewLblcount)

let scrollView: UIScrollView = UIScrollView(frame: CGRectMake(20, 30, 320, 250 * floatValue))

for i in 0 ..< viewsCount {
    let views: UIView = UIView(frame: CGRectMake(0, 320 * CGFloat(i) + floatValue, self.view.frame.size.width - 40, 300))
    views.backgroundColor = UIColor.grayColor()
    views.tag = i + 1

    for j in 0 ..< viewLblcount {
        let label = UILabel(frame: CGRectMake(20, 40 * CGFloat(j) + floatLbl, self.view.frame.size.width - 100, 20))
        let label2 = UILabel(frame: CGRectMake(10, 90 * CGFloat(j) + floatLbl, self.view.frame.size.width - 100, 30))

        label.backgroundColor = UIColor.cyanColor()
        label.text = "iOS LABEL TRY"

        label2.backgroundColor = UIColor.magentaColor()
        label2.text = "iOS LABEL TRY2"

        label.tag = j + 1
        label2.tag = j + 1

        views.addSubview(label)
        views.addSubview(label2)

        scrollView.addSubview(views)
        self.view!.addSubview(scrollView)
        scrollView.contentSize = CGSizeMake(310, 390 * floatValue)
    }

All the label is showing same text.

Upvotes: 1

Views: 712

Answers (2)

user212514
user212514

Reputation: 3130

You have the text of the labels hardcoded on these lines:

label.text = "iOS LABEL TRY"
label2.text = "iOS LABEL TRY2"

I'm not exactly sure what text you want in each label, but I think you want to change it to:

label.text = messageForLbl[j]

Also, you can avoid a future bug by using Swift's enumerators (then you don't have to change viewLblcount when you change messageForLbl):

for value in messageForLbl.enumerate() {
    label.text = value
}

Upvotes: 2

Vikas Jindal
Vikas Jindal

Reputation: 21

Because you have hard coded the text

label.text = "iOS LABEL TRY"

Upvotes: 0

Related Questions