简体   繁体   中英

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 UILabel s 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.

在此处输入图片说明 在此处输入图片说明

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
}

Use of tag View can solve this issue. TagListView is an external library. When u add a view as subclass of taglistView, its height automatically increases accordingly.

ADD this to pod file : pod 'TagListView'

func addTags() {
        let str1 = "Hi"
        tagListView.addTag(str1)
        let str2 = "Helloo"
            tagListView.addTag(str2)
        let str3 = "How Are u ? "
        tagListView.addTag(str2)
        tagListView.isUserInteractionEnabled = false
    }

You cannot do that with constraints only. To change the entire position of the element on the screen, you need to do it programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM