iOS富文本(NSAttributedString)

參考
iOS中關于AttributedString的那些事兒
iOS 7中文字排版和渲染引擎——Text Kit

富文本的所有屬性

    //NSFontAttributeName   字號 UIFont 默認12
    //NSParagraphStyleAttributeName    段落樣式  NSParagraphStyle
    //NSForegroundColorAttributeName    前景色   UIColor
    //NSBackgroundColorAttributeName    背景色   UIColor
    //NSObliquenessAttributeName        字體傾斜     NSNumber
    //NSExpansionAttributeName          字體加粗     NSNumber  比例 0就是不變 1增加一倍
    //NSKernAttributeName               字間距   CGFloat
    //NSUnderlineStyleAttributeName     下劃線     1或0
    //NSUnderlineColorAttributeName     下劃線顏色
    //NSStrikethroughStyleAttributeName 刪除線   1或0
    //NSStrikethroughColorAttributeName 某種顏色
    //NSStrokeColorAttributeName        same as ForegroundColor
    //NSStrokeWidthAttributeName        CGFloat
    //NSLigatureAttributeName           連筆字  1或0  沒看出效果
    // NSStrokeWidthAttributeName         設置筆畫寬度,取值為 NSNumber 對象(整數),負值填充效果,正值中空效果
    //NSShadowAttributeName             陰影    NSShawdow
    //NSTextEffectAttributeName          設置文本特殊效果,取值為 NSString 對象,目前只有圖版印刷效果可用:
    //NSAttachmentAttributeName         NSTextAttachment  設置文本附件,常用插入圖片
    //NSLinkAttributeName               鏈接  NSURL (preferred) or NSString
    //NSBaselineOffsetAttributeName     基準線偏移   NSNumber

    //NSWritingDirectionAttributeName   文字方向     @[@(1),@(2)]  分別代表不同的文字出現方向等等,我想你一定用不到它 - -
    //NSVerticalGlyphFormAttributeName  水平或者豎直文本  1豎直 0水平 在iOS沒卵用,不支持豎版
NSAttributedString
@property (readonly, copy) NSString *string;
- (NSDictionary<NSString *, id> *)attributesAtIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range;
@property (readonly) NSUInteger length;
- (nullable id)attribute:(NSString *)attrName atIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range;
- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range;

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

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

- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)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 (NS_NOESCAPE ^)(NSDictionary<NSString *, id> *attrs, NSRange range, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(id _Nullable value, NSRange range, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
@interface NSMutableAttributedString : NSAttributedString

- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;
- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)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<NSString *, id> *)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
段落樣式

段落樣式主要改行距、段距、首行縮進、最大最小行高、多倍行距等十幾個屬性,把這些總結了你就比我更全..

    //NSMutableParagraphStyle 同 NSParagraphStyle
    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc]init];
    muParagraph.lineSpacing = 10; // 行距
    muParagraph.paragraphSpacing = 20; // 段距
    muParagraph.firstLineHeadIndent = 30; // 首行縮進
    paragraphStyle.alignment = NSTextAlignmentJustified;//(兩端對齊的)文本對齊方式:(左,中,右,兩端對齊,自然)    
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//結尾部分的內容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")    
    paragraphStyle.headIndent = 20;//整體縮進(首行除外)    
    paragraphStyle.tailIndent = 20;//    
    paragraphStyle.minimumLineHeight = 10;//最低行高    
    paragraphStyle.maximumLineHeight = 20;//最大行高    
    paragraphStyle.paragraphSpacing = 15;//段與段之間的間距    
    paragraphStyle.paragraphSpacingBefore = 22.0f;//段首行空白空間/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */    
    paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;//從左到右的書寫方向(一共??三種)    
    paragraphStyle.lineHeightMultiple = 15;/* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */    
    paragraphStyle.hyphenationFactor = 1;//連字屬性 在iOS,唯一支持的值分別為0和1
附件(圖片)
    NSTextAttachment *attachment=[[NSTextAttachment alloc] initWithData:nil ofType:nil];
    UIImage *img=[UIImage imageNamed:@"test.png"];
    attachment.image=img;
    attachment.bounds=CGRectMake(0, 0, 20, 20);
    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
加載HTML標簽文本
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
參數options里面的字典有三對key value
 NSPlainTextDocumentType  // 普通文本
 NSRTFTextDocumentType   //  富文本
 NSRTFDTextDocumentType   // 帶附件的富文本
 NSHTMLTextDocumentType  // 這個可以加載HTML格式的文本

UITextView

@property(nonatomic) NSRange selectedRange;
@property(null_resettable,copy) NSAttributedString *attributedText 
@property(nonatomic,copy) NSDictionary<NSString *, id> *typingAttributes NS_AVAILABLE_IOS(6_0); // automatically resets when the selection changes
- (void)scrollRangeToVisible:(NSRange)range;
@property (nullable, readwrite, strong) UIView *inputView;             
@property (nullable, readwrite, strong) UIView *inputAccessoryView;
// 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,strong) NSTextStorage *textStorage NS_AVAILABLE_IOS(7_0);
@property(nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0) __TVOS_PROHIBITED;
@protocol UITextViewDelegate <NSObject, UIScrollViewDelegate>
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- (void)textViewDidChangeSelection:(UITextView *)textView;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容