iOS開發(fā)常見問題-富文本NSAttributedString

NSAttributedString

  • 帶有屬性的字符串, 富文本
  • 由2部分組成
    • 文字內(nèi)容 : NSString *
    • 文字屬性 : NSDictionary *
      • 文字顏色 - NSForegroundColorAttributeName
      • 字體大小 - NSFontAttributeName
      • 下劃線 - NSUnderlineStyleAttributeName
      • 背景色 - NSBackgroundColorAttributeName
  • 初始化
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor yellowColor];
attributes[NSBackgroundColorAttributeName] = [UIColor redColor];
attributes[NSUnderlineStyleAttributeName] = @YES;
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"123" attributes:attributes];
  • 使用場合
    • UILabel - attributedText
    • UITextField - attributedPlaceholder

NSMutableAttributedString

  • 繼承自NSAttributedString
  • 常見方法
// 設(shè)置range范圍的屬性, 重復(fù)設(shè)置同一個范圍的屬性, 最后一次設(shè)置才是有效的(之前的設(shè)置會被覆蓋掉)
- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
// 添加range范圍的屬性, 同一個范圍, 可以不斷累加屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容