简体   繁体   中英

How to truncate UILabel with sizeToFit enabled?

How can I get this label to truncate with ellipsis while retaining its sizeToFit attribute? In effect, I want the label to size itself based on its content while having a maximum width. The label is contained in a UIView with clipsToBounds enabled.

label.text = labelText
label.sizeToFit()
label.frame.origin.y = 16
label.frame.origin.x = 16
label.lineBreakMode = .byTruncatingTail
label.numberOfLines = 1

If I understand what you want, after calling sizeToFit , set the label's width to whatever maximum width you want.

label.text = labelText
label.lineBreakMode = .byTruncatingTail
label.numberOfLines = 1
label.sizeToFit()
label.frame.origin.y = 16
label.frame.origin.x = 16
if label.frame.width > someMaximumWidth {
    label.frame.size.width = someMaximumWidth
}

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