UITextView Alternative

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 11:35: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.



来源:https://stackoverflow.com/questions/13932550/uitextview-alternative

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