UITextView Alternative

2019-08-14 15:56发布

问题:

As i understood from Apple docs attributedText property of UITextView:

This property is nil by default. Assigning a new value to this property also replaces the value of the text property with the same string data, albeit without any formatting information. In addition, assigning a new a value updates the values in the font, textColor, and textAlignment properties so that they reflect the style information starting at location 0 in the attributed string.

Therefore i cannot add an attributedString by code with multiple Attributes at different locations.

Can someone please help me create the following effect by code in iOS6? This is possible using nib files and by changing range attributes for text parts in UITextView but i cant seem to reproduce the effect by code.

<'font systemFontOfSize=18>Desired<'/font> effect <'textColor = [UIColor redColor]> to be written b<'/textColor>y code.

Suppose the tags correspond to attributes.

P.S. I don't want to use CATextLayers since i am trying to use the AutoLayout feature with the UITextView.

回答1:

You can build an NSAttributedString with an NSDictionary containing all of the attributes you need:

NSAttributedString* attString = [[NSAttributedString alloc] 
               initWithString: @"Desired effect to be written by code" 
                   attributes: (NSDictionary*)attributes];

Or use it's mutable subclass NSMutableAttributedString:

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]  
               initWithString: @"Desired effect to be written by code"];

    [attString addAttribute: NSForegroundColorAttributeName 
                      value: [UIColor redColor] 
                      range: NSMakeRange(15,15)];

...etc
then...

myTextView.attributedText = attString;

Each attribute is applied to an NSRange (location, length) of the string. Distinct attribute types (eg colour, font size) can overlap different ranges.

update
Use the NSMutableAttributedString example. NSAttributedString's initWithString:attributes will apply attributes across the entire range of the string, which is what you are trying to avoid, sorry for confusion.