3

In my App i have a UItextView and its input view has accessory view with couple of buttons on it.

I am trying to change the text already being typed to underline text. Its working fine but its loosing the font and the font size after conversion.

Here's what i am doing:

NSRange selectedRange = [self.commentsTextView selectedRange];

            NSDictionary *currentAttributesDict = [self.commentsTextView.textStorage attributesAtIndex:selectedRange.location
                                                                            effectiveRange:nil];

            NSDictionary *dict;

            if ([currentAttributesDict objectForKey:NSUnderlineStyleAttributeName] == nil ||
                [[currentAttributesDict objectForKey:NSUnderlineStyleAttributeName] intValue] == 0) {

                dict = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInt:1]};

            }
            else{
                dict = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInt:0]};
            }

            [self.commentsTextView.textStorage beginEditing];
            [self.commentsTextView.textStorage setAttributes:dict range:selectedRange];
            [self.commentsTextView.textStorage endEditing];
Ashutosh
  • 5,614
  • 13
  • 52
  • 84

1 Answers1

2

You're setting the attributes for that range of text using a dictionary that only has a value for NSUnderlineStyleAttributeName.

In your if... else structure, in addition to NSUnderlineStyleAttributeName give dict the values that you want for the font and font size.

How did you previously set the font and font size?

From Apple's doc on UITextView the Overview section:

In iOS 6 and later, this class supports multiple text styles through use of the attributedText property. (Styled text is not supported in earlier versions of iOS.) Setting a value for this property causes the text view to use the style information provided in the attributed string. You can still use the font, textColor, and textAlignment properties to set style attributes, but those properties apply to all of the text in the text view.

https://developer.apple.com/library/ios/documentation/uikit/reference/uitextview_class/Reference/UITextView.html

When you set the attributes for a specific range of text, it will overwrite any styles that previously existed in that range, using the new attributes only.

Gavin Hope
  • 2,173
  • 24
  • 38