iOS NSAttributedString

簡介本人是一個iOS開發(fā)菜鳥,之前很是懶惰短绸,以后希望以此來激勵自己筹裕,每天對掌握的新知識點(diǎn)進(jìn)行記錄,激勵自己也想分享一下朝卒!不怕錯,更不怕批囚企!只為自己好好的學(xué)習(xí)留下點(diǎn)努力的痕跡瑞眼!

NSAttributedString實(shí)際上就是一個字符串和一本字典。字典包含每一個字符的屬性:包括字體伤疙、大小辆影、下劃線黍特、顏色等等。關(guān)鍵是要知道字典中每個key的含義以及相應(yīng)value的取值范圍次慢。

<font color=#0099ff size=5 face="黑體">Character Attributes(重點(diǎn))</font>

NSString *const  NSFontAttributeName ;                   // 設(shè)置字體翔曲,UIFont對象,默認(rèn)12-point Helvetica(Neue)
NSString *const  NSParagraphStyleAttributeName ;         // (重要)設(shè)置段落風(fēng)格部默,NSParagraphStyle對象,默認(rèn)是[NSParagraphStyle defaultParagraphStyle]傅蹂,這里可以設(shè)置很多段落格式,首行縮進(jìn)之類的
NSString *const  NSForegroundColorAttributeName ;        // 字體顏色犁功,UIColor對象硼一,默認(rèn)黑色
NSString *const  NSBackgroundColorAttributeName ;        // 背景色,UIColor對象案糙,默認(rèn)透明
NSString *const  NSLigatureAttributeName ;               // <span style="color:#FF0000;">(********)不知道干嘛用</span>
NSString *const  NSKernAttributeName ;                   // 字符間距,NSNumber 浮點(diǎn)數(shù)时捌,默認(rèn)為0
NSString *const  NSStrikethroughStyleAttributeName ;     // 刪除線的線粗,NSNumber 整數(shù)奢讨,默認(rèn)是NSUnderlineStyleNone(你真的沒看錯)
NSString *const  NSUnderlineStyleAttributeName ;         // 下劃線的線粗,NSNumber 整數(shù)拿诸,默認(rèn)同上,還有別的樣式亩码,例如雙下劃線
NSString *const  NSStrokeColorAttributeName ;            // 描邊顏色,UIColor對象蚀同,默認(rèn)同字體顏色
NSString *const  NSStrokeWidthAttributeName ;            // 描邊缅刽,NSNumber 浮點(diǎn)數(shù)蠢络,正值表示鏤空描邊,負(fù)值標(biāo)志填充描邊啡省,值表示描邊線粗
NSString *const  NSShadowAttributeName ;                 // 陰影髓霞,NSShadow對象,效果參照最后的圖片
NSString *const  NSTextEffectAttributeName ;             // 文本風(fēng)格结序,NSSting對象,默認(rèn)為nil徐鹤,官方舉例NSTextEffectLetterpressStyle邀层,其實(shí)也就只有這個風(fēng)格。寥院。。感覺有跟沒有差不多
NSString *const  NSAttachmentAttributeName ;             // <span style="color:#FF0000;">(********)文本附件屬性</span>凛澎, NSTextAttachment對象,其中包含有圖片预厌,等我找到典型案例再回來重新介紹
NSString *const  NSLinkAttributeName ;                   // 鏈接某個地址元媚,NSURL(推薦)或NSString對象刊棕,默認(rèn)為nil不指定任何鏈接待逞。這里有詳細(xì)介紹,http://blog.csdn.net/reylen/article/details/18958995
NSString *const  NSBaselineOffsetAttributeName ;         // 基線偏移量识樱,NSNumber 浮點(diǎn)數(shù)震束,可以上下微調(diào)字體的位置垢村。(適合那些返回位置信息不正確的字體)
NSString *const  NSUnderlineColorAttributeName ;         // 下劃線顏色
NSString *const  NSStrikethroughColorAttributeName ;     // 刪除線顏色
NSString *const  NSObliquenessAttributeName ;            // 斜體嚎卫,NSNumber 浮點(diǎn)數(shù),默認(rèn)0侵佃,數(shù)值表示傾斜度
NSString *const  NSExpansionAttributeName ;              // 水平拉伸,NSNumber 浮點(diǎn)數(shù)馋辈,默認(rèn)0倍谜,水平拉伸字體,高度不變枢劝。
NSString *const  NSWritingDirectionAttributeName ;       // <span style="color:#FF0000;">(********)</span>書寫方向,NSArray NSNumber(而且只能是整數(shù)0烙常,1鹤盒,2,3)侦锯,沒看到什么效果,找到案例再來更新
NSString *const  NSVerticalGlyphFormAttributeName;       // 水平或垂直顯示尺碰,NSNumber(只有0:水平和1:垂直),沒看到效果洛心。题篷。。

Text Writing Direction

用于"NSWritingDirectionAttributeName"

Text Writing Direction

用于"NSWritingDirectionAttributeName"

Text Effect Attribute

用于"NSTextEffectAttributeName"

Text Effect Attribute

用于"NSTextEffectAttributeName"

Underline and Strikethrough Style Attributes

用于"NSUnderlineStyleAttributeName"和"NSStrikethroughStyleAttributeName"

typedef enum : NSInteger  {
   NSUnderlineStyleNone  = 0x00 ,
   NSUnderlineStyleSingle  = 0x01 ,
   NSUnderlineStyleThick  = 0x02 ,
   NSUnderlineStyleDouble  = 0x09 ,
   NSUnderlinePatternSolid  = 0x0000 ,
   NSUnderlinePatternDot  = 0x0100 ,
   NSUnderlinePatternDash  = 0x0200 ,
   NSUnderlinePatternDashDot  = 0x0300 ,
   NSUnderlinePatternDashDotDot  = 0x0400 ,
   NSUnderlineByWord  = 0x8000 
} NSUnderlineStyle;

String Drawing Options

enum {
   NSStringDrawingTruncatesLastVisibleLine  = 1 << 5,
   NSStringDrawingUsesLineFragmentOrigin  = 1 << 0,
   NSStringDrawingUsesFontLeading  = 1 << 1,
   NSStringDrawingUsesDeviceMetrics  = 1 << 3,
};
typedef NSInteger  NSStringDrawingOptions;

Document Types

NSString  *NSPlainTextDocumentType;
NSString  *NSRTFTextDocumentType;
NSString  *NSRTFDTextDocumentType;
NSString  *NSHTMLTextDocumentType;

Keys for Options and Document Attributes Dictionaries

NSString *const  NSDocumentTypeDocumentAttribute ;
NSString *const  NSCharacterEncodingDocumentAttribute ;
NSString *const  NSDefaultAttributesDocumentAttribute ;
NSString *const  NSPaperSizeDocumentAttribute ;
NSString *const  NSPaperMarginDocumentAttribute ;
NSString *const  NSViewSizeDocumentAttribute ;
NSString *const  NSViewZoomDocumentAttribute ;
NSString *const  NSViewModeDocumentAttribute ;
NSString *const  NSReadOnlyDocumentAttribute ;
NSString *const  NSBackgroundColorDocumentAttribute ;
NSString *const  NSHyphenationFactorDocumentAttribute ;
NSString *const  NSDefaultTabIntervalDocumentAttribute ;
NSString *const  NSTextLayoutSectionsAttribute;

Text Layout Sections Attribute

NSString  *NSTextLayoutSectionOrientation;
NSString  *NSTextLayoutSectionRange;

**NSString的屬性常量法严,貌似部分可以用在Character Attributes里面
**
UILineBreakMode已由NSLineBreakMode代替。Keys for Text Attributes Dictionaries已在ios 7中被拋棄拗馒。剩下以下三類常量可以使用墓塌。

NSTextAlignment:

enum {  
   NSTextAlignmentLeft       = 0,  
   NSTextAlignmentCenter     = 1,  
   NSTextAlignmentRight      = 2,  
   NSTextAlignmentJustified  = 3,   // 兩端對齊  
   NSTextAlignmentNatural    = 4,  
};  
typedef NSInteger  NSTextAlignment;  

UIBaselineAdjustment:

用于"NSBaselineOffsetAttributeName"字符屬性

typedef enum {  
   UIBaselineAdjustmentAlignBaselines ,   // 根據(jù)文字的baseLine調(diào)整  
   UIBaselineAdjustmentAlignCenters ,     // 根據(jù)框的水平中心線調(diào)整  
   UIBaselineAdjustmentNone ,             // 以左上角為基準(zhǔn),默認(rèn)對齊方式  
} UIBaselineAdjustment;  

NSWritingDirection:

enum {  
   NSWritingDirectionNatural  = -1,      // Use the Unicode Bidi algorithm rules P2 and P3 to determine which direction to use.  
   NSWritingDirectionLeftToRight  =  0,  // 從左到右  
   NSWritingDirectionRightToLeft  =  1   // 從右到左  
};  

UITextViewDelegate調(diào)用流程:

1.點(diǎn)擊TextView內(nèi)部访诱,出現(xiàn)光標(biāo)前韩肝。

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;  

如果返回NO,則不會進(jìn)入編輯涡相,不會出現(xiàn)光標(biāo)剩蟀,也不會調(diào)用textViewDidBeginEditing:方法。

當(dāng)選定點(diǎn)選字符串中其他位置丙号,還是會調(diào)用didChangeSelection方法

2.出現(xiàn)光標(biāo)后

- (void)textViewDidBeginEditing:(UITextView *)textView;  

3.移動光標(biāo)或選定某些字符串

- (void)textViewDidChangeSelection:(UITextView *)textView;  

4.添加缰冤、刪除一個字符

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;  
- (void)textViewDidChangeSelection:(UITextView *)textView;  
- (void)textViewDidChange:(UITextView *)textView;  

如果第1個方法返回NO棉浸,不會調(diào)用下面兩個方法怀薛。

5.不知道怎么結(jié)束編輯迷郑。。鼓择。先留著就漾。(***)


附類定義

UITextView

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextView : UIScrollView <UITextInput>

@property(nonatomic,assign) id<UITextViewDelegate> delegate;    // 代理
@property(nonatomic,copy) NSString *text;
@property(nonatomic,retain) UIFont *font;
@property(nonatomic,retain) UIColor *textColor;
@property(nonatomic) NSTextAlignment textAlignment;    // default is NSLeftTextAlignment

@property(nonatomic) NSRange selectedRange;
@property(nonatomic,getter=isEditable) BOOL editable;
@property(nonatomic,getter=isSelectable) BOOL selectable NS_AVAILABLE_IOS(7_0); // toggle selectability, which controls the ability of the user to select content and interact with URLs & attachments
@property(nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);

@property(nonatomic) BOOL allowsEditingTextAttributes NS_AVAILABLE_IOS(6_0); // defaults to NO
@property(nonatomic,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0); // default is nil
@property(nonatomic,copy) NSDictionary *typingAttributes NS_AVAILABLE_IOS(6_0); // automatically resets when the selection changes

- (void)scrollRangeToVisible:(NSRange)range;


// Presented when object becomes first responder.  If set to nil, reverts to following responder chain.  If
// set while first responder, will not take effect until reloadInputViews is called.
@property (readwrite, retain) UIView *inputView;             
@property (readwrite, retain) UIView *inputAccessoryView;

@property(nonatomic) BOOL clearsOnInsertion NS_AVAILABLE_IOS(6_0); // defaults to NO. if YES, the selection UI is hidden, and inserting text will replace the contents of the field. changing the selection will automatically set this to NO.

// Create a new text view with the specified text container (can be nil) - this is the new designated initializer for this class
- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer NS_AVAILABLE_IOS(7_0);

// Get the text container for the text view
@property(nonatomic,readonly) NSTextContainer *textContainer NS_AVAILABLE_IOS(7_0);
// Inset the text container's layout area within the text view's content area
@property(nonatomic, assign) UIEdgeInsets textContainerInset NS_AVAILABLE_IOS(7_0);

// Convenience accessors (access through the text container)
@property(nonatomic,readonly) NSLayoutManager *layoutManager NS_AVAILABLE_IOS(7_0);
@property(nonatomic,readonly,retain) NSTextStorage *textStorage NS_AVAILABLE_IOS(7_0);

// Style for links
@property(nonatomic, copy) NSDictionary *linkTextAttributes NS_AVAILABLE_IOS(7_0);

@end

UIKIT_EXTERN NSString * const UITextViewTextDidBeginEditingNotification;
UIKIT_EXTERN NSString * const UITextViewTextDidChangeNotification;
UIKIT_EXTERN NSString * const UITextViewTextDidEndEditingNotification;

NSAttributedString

@interface NSAttributedString : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>

@property (readonly, copy) NSString *string;
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;

@end

@interface NSAttributedString (NSExtendedAttributedString)

@property (readonly) NSUInteger length;
- (id)attribute:(NSString *)attrName atIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;
- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range;

- (NSDictionary *)attributesAtIndex:(NSUInteger)location longestEffectiveRange:(NSRangePointer)range inRange:(NSRange)rangeLimit;
- (id)attribute:(NSString *)attrName atIndex:(NSUInteger)location longestEffectiveRange:(NSRangePointer)range inRange:(NSRange)rangeLimit;

- (BOOL)isEqualToAttributedString:(NSAttributedString *)other;

- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;

typedef NS_OPTIONS(NSUInteger, NSAttributedStringEnumerationOptions) {
  NSAttributedStringEnumerationReverse = (1UL << 1),
  NSAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20)
};

- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(id value, NSRange range, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);

@end

NS_CLASS_AVAILABLE(10_0, 3_2)
@interface NSMutableAttributedString : NSAttributedString

- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

@end

@interface NSMutableAttributedString (NSExtendedMutableAttributedString)

@property (readonly, retain) NSMutableString *mutableString;

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
- (void)removeAttribute:(NSString *)name range:(NSRange)range;

- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;
- (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc;
- (void)appendAttributedString:(NSAttributedString *)attrString;
- (void)deleteCharactersInRange:(NSRange)range;
- (void)setAttributedString:(NSAttributedString *)attrString;

- (void)beginEditing;
- (void)endEditing;

@end

代理協(xié)議UITextViewDelegate

@protocol UITextViewDelegate <NSObject, UIScrollViewDelegate>

@optional

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
- (BOOL)textViewShouldEndEditing:(UITextView *)textView;

- (void)textViewDidBeginEditing:(UITextView *)textView;
- (void)textViewDidEndEditing:(UITextView *)textView;

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- (void)textViewDidChange:(UITextView *)textView;

- (void)textViewDidChangeSelection:(UITextView *)textView;

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0);
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0);

@end


NSShadow

NS_CLASS_AVAILABLE_IOS(6_0) @interface NSShadow : NSObject <NSCopying, NSCoding>

@property (nonatomic, assign) CGSize shadowOffset;      // 影子與字符串的偏移量
@property (nonatomic, assign) CGFloat shadowBlurRadius; // 影子的模糊程度
@property (nonatomic, retain) id shadowColor;           // 影子的顏色

@end

shadow屬性的效果

NSShadow *shadow = [[NSShadow alloc]init];  
    shadow.shadowOffset = CGSizeMake(5, 5);     // 影子偏移量  
    shadow.shadowColor = [UIColor blueColor];   // 影子顏色  
    shadow.shadowBlurRadius = 20.0;             // 模糊程度  
      
      
    NSDictionary *dict = @{  
                           NSFontAttributeName:[UIFont fontWithName:@"Marion-Italic" size:50.0],  
                           NSShadowAttributeName:shadow,  
                           NSKernAttributeName:@(2)  
                           };  
    textView.attributedText = [[NSAttributedString alloc]initWithString:@"中文究竟是\nEnglishReally" attributes:dict];  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末摆出,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子首妖,更是在濱河造成了極大的恐慌偎漫,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件有缆,死亡現(xiàn)場離奇詭異象踊,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)棚壁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進(jìn)店門杯矩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人袖外,你說我怎么就攤上這事史隆。” “怎么了曼验?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵泌射,是天一觀的道長。 經(jīng)常有香客問我鬓照,道長熔酷,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮翼抠,結(jié)果婚禮上阴颖,老公的妹妹穿的比我還像新娘量愧。我一直安慰自己偎肃,他們只是感情好浑此,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布料饥。 她就那樣靜靜地躺著朱监,像睡著了一般巡蘸。 火紅的嫁衣襯著肌膚如雪悦荒。 梳的紋絲不亂的頭發(fā)上逾冬,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天,我揣著相機(jī)與錄音嘀趟,去河邊找鬼愈诚。 笑死炕柔,一個胖子當(dāng)著我的面吹牛匕累,可吹牛的內(nèi)容都是我干的衰琐。 我是一名探鬼主播羡宙,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼狗热,長吁一口氣:“原來是場噩夢啊……” “哼指攒!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起虑啤,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎叉寂,沒想到半個月后屏鳍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體钓瞭,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡堤结,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了瘾带。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片月弛。...
    茶點(diǎn)故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡贞绵,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出章母,到底是詐尸還是另有隱情乳怎,我是刑警寧澤蚪缀,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站金蜀,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏苗傅。R本人自食惡果不足惜嘶炭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望睡陪。 院中可真熱鬧,春花似錦炬称、人聲如沸据德。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽裹唆。三九已至劳坑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背舀武。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工跛梗, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留诚欠,地道東北人。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像业崖,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子妇斤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內(nèi)容