Search code examples
iosuitextviewnsattributedstringtext-alignment

How to get the cursor in an UITextView to reflect an updated typingAttributes for paragraph alignment?


I am using a UITextView to enter some rich text. I have created a button to change the paragraph alignment (left, center, right).

I am applying the alignment to the attributedText when the user selects some text and it works as expected.

However, when the user hit return and is in a new, zero-length paragraph (just after a newline and nothing following), I believe I should change the typingAttributes to reflect the attributes I want the new text to receive.

I used the following code:

if ((paragraphRange.length == 0) && (paragraphRange.location == [mutableText length])) {

    NSMutableParagraphStyle * mutableParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

    [mutableParagraphStyle setAlignment:textAlignment];
    [mutableParagraphStyle setLineBreakMode:NSLineBreakByWordWrapping];

    NSMutableDictionary * attributes = [self.typingAttributes mutableCopy];
    [attributes setObject:mutableParagraphStyle forKey:NSParagraphStyleAttributeName];
    self.typingAttributes = attributes;

It does apply the paragraph alignment once the character is typed, but the cursor in the UITextView does not reflect the change until after the character is typed. I am looking for a mechanism to get the cursor into the right place before the text is typed. For example, if the user selects 'centered', I want the cursor to move to the center of the view to show where the text will do.

Anyone have any ideas on how to do this?

Thanks in advance,

Charlie


Solution

  • For those tracking this, it looks like this is a bug in iOS7. The renderer does not appear to take into account the state of the typingAttributes paragraph alignment when computing the location of the cursor.

    Looks like this one needs a bug report to Apple ;-)