How can I horizontally center a single line of text in UITextView?

浪子不回头ぞ 提交于 2019-12-12 16:13:33

问题


I have a UITextView which displays a fair amount of text. I need to horizontally center some, but not all, of the lines of text in the text view.

I've tried setting the NSParagraphStyleAttributeName with an NSParagraphStyle instance whose alignment property is NSTextAlignmentCenter on the range of the line to be centered. I'm also setting the font so the centered line is bold. When I do this using the code below, the relevant line is bolded, but remains left aligned.

if (shouldCenterLine) {
    NSMutableParagraphStyle *centerStyle = [[NSMutableParagraphStyle alloc] init];
    centerStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *attributes = @{NSParagraphStyleAttributeName : centerStyle,
                                 NSFontAttributeName : boldFont};
    [attributedString setAttributes:attributes range:lineRange];
}

If I apply this same paragraph style attribute to the entire contents of the text view, the text ends up centered as expected.

Is it possible to convince UITextView to center specific subranges of its text? Is the only solution to move to a UIWebView rendering generated HTML? Note that this is for an app still supporting iOS 6, so unfortunately I'm not able to use Text Kit.


回答1:


Try including the line returns around the the line that you'd like centered within the range that you apply the style to.



来源:https://stackoverflow.com/questions/21128306/how-can-i-horizontally-center-a-single-line-of-text-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!