Search code examples
iosobjective-cswiftautolayoutios-autolayout

UILabel on second line if the content doesn't fit in the view's first line


The best way to describe my situations is with images. What I have is a view which contains several UILabels and UIImage. The red box is a UILabel and if the content is too big it should go to the second line.

From the storyboard I have a working case when the content fits but the problem is that I am not sure how to handle the case when the last (red box) should go to the second line. I am using autolayout and cartography.

If someone can point me to the right direction I will be very grateful.

enter image description here enter image description here


Solution

  • First calcululate width of text as per your current label's position.

    If text width is more than current label's width then see my answer from below link:

    Auto Layout how to move the view2 from right to the bottom?

    Calculate width:

    func widthForView1(_ text:String, font:UIFont, height:CGFloat) -> CGFloat
    {
    
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: your_label_width, height: your_lable_height))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.text = text
    label.font = font
    label.sizeToFit()
    return label.frame.width
    }