Frage

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.

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top