Search code examples
iosswiftuilabelsizetofit

UILabel sizeToFit doesn't stretch to width


I am programmatically creating a UILabel like this:

    hashtagLbl = UILabel(frame: CGRectMake(20, nameLbl.frame.maxY + 5,
    bounds.width-40, layerView.frame.width/3.66))
    hashtagLbl.text = "#Placeholder"
    hashtagLbl.font = UIFont.systemFontOfSize(18)
    hashtagLbl.textColor = UIColorFromRGB(0x9B9B9B)
    hashtagLbl.sizeToFit()
    hashtagLbl.numberOfLines = 0
    hashtagLbl.lineBreakMode = NSLineBreakMode.ByWordWrapping

Now I am loading data and setting the data to the label and I am recalling the sizeToFit:

        if let text = memberHashtags{
        hashtagLbl.text = text
        hashtagLbl.sizeToFit()

    }

Rather than displaying like this (UILabel created in IB): enter image description here

the label is displaying like this:

enter image description here


Solution

  • try to call

    hashtagLbl.sizeToFit()
    

    as last statement in your code