简体   繁体   中英

Indent second line of UILabel

So I have a UILabel that may or may not go to a second line, depending if it is on iPhone or iPad. What I would like to accomplish is to have it indent on the second line to line up correctly, if needed.

On iPad it will almost never need the second line break, and depending on which iPhone it is running on, it may or may not. So, in essence, I need a way to dynamically indent the second line, only when there is a second line.

Use an NSAttributedString for your label, and set the headIndent of its paragraph style :

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.headIndent = 14;
NSDictionary *attributes = @{
    NSParagraphStyleAttributeName: style
};
NSAttributedString *richText = [[NSAttributedString alloc] initWithString:@"So this UILabel walks into a bar…" attributes:attributes];
self.narrowLabel.attributedText = richText;
self.wideLabel.attributedText = richText;

Result:

示例结果

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