在iOS開發中,常常會有一段文字顯示不同的顏色和字體,或者給某幾個文字加刪除線或下划線的需求。之前在網上找了一些資料,有的是重繪UILabel的textLayer,有的是用html5實現的,都比較麻煩,而且很多UILabel的屬性也不起作用了,效果都不理想。后來了解到NSMuttableAttstring(帶屬性的字符串),上面的一些需求都可以很簡便的實現。
NSMuttableAttstring 方法
為某一范圍內文字設置多個屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
為某一范圍內文字添加某個屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
為某一范圍內文字添加多個屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某范圍內的某個屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
常見的屬性及說明
NSFontAttributeName 字體
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字體顏色
NSBackgroundColorAttributeName 背景顏色
NSStrikethroughStyleAttributeName 刪除線格式
NSUnderlineStyleAttributeName 下划線格式
NSStrokeColorAttributeName 刪除線顏色
NSStrokeWidthAttributeName 刪除線寬度
NSShadowAttributeName 陰影
例子一:
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)]; testLabel.backgroundColor = [UIColor lightGrayColor]; testLabel.textAlignment = NSTextAlignmentCenter; NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"今天天氣不錯呀"]; [AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16.0] range:NSMakeRange(2, 2)]; [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(2, 2)]; testLabel.attributedText = AttributedStr; [self.view addSubview:testLabel];
效果:

例子二:
UILabel *titleView = [[UILabel alloc] init]; titleView.width = 200; titleView.height = 100; titleView.textAlignment = NSTextAlignmentCenter; // 自動換行 titleView.numberOfLines = 0; titleView.y = 50; NSString *str = [NSString stringWithFormat:@"%@\n%@", prefix, name]; // 創建一個帶有屬性的字符串(比如顏色屬性、字體屬性等文字屬性) NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str]; // 添加屬性 [attrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:[str rangeOfString:prefix]]; [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:[str rangeOfString:name]]; titleView.attributedText = attrStr;
例子二中,range:[str rangeOfString:name] 找到name 有str 所在的范圍。
刪除:
NSString *marketPrice = [NSString stringWithFormat:@"¥%d",4302]; NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:marketPrice]; [attrStr addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, marketPrice.length)];
文字換行
UILabel *tips = [[UILabel alloc]initWithFrame:CGRectMake(20, 16, kScreenWidth - 20, 45)]; [tips setTextColor:[UIColor grayColor]]; [tips setText:@"支付密碼必須為6位數字組合。\n您可依次進入 '功能列表' -> '安全中心' 修改支付密碼。"]; [tips setFont:[UIFont boldSystemFontOfSize:12]]; tips.textAlignment = NSTextAlignmentLeft; tips.numberOfLines = 0; // 關鍵一句
參考博客:http://snowyshell.blog.163.com/blog/static/2209140342014475383375/
