• NSMutableAttributedString iOS 在UILabel显示不同的字体和颜色(转)


    在项目开发中,我们经常会遇到在这样一种情形:在一个UILabel 使用不同的颜色或不同的字体来体现字符串,在iOS 6 以后我们可以很轻松的实现这一点,官方的API 为我们提供了UILabel类的attributedText, 使用不同颜色和不同字体的字符串,我们可以使用NSAttributedText 和 NSMutableAttributedText 类来实现。
    
    现实代码:
    
    
    @interface ViewController : UIViewController
    @property (nonatomic, strong) IBOutlet UILabel *attrLabel;
    - (IBAction)next:(id)sender;
    @end
     .m文件 在viewDidLoad方法中添加以下代码:
    
    
    self.title = @"For iOS 6 & later";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];
    attrLabel.attributedText = str;
    NSString *const NSForegroundColorAttributeName;//值为UIColor,字体颜色,默认为黑色。
    
    
    NSString *const NSBackgroundColorAttributeName;//值为UIColor,字体背景色,默认没有。
    
    
    NSString *const NSLigatureAttributeName;//值为整型NSNumber,连字属性,一般中文用不到,在英文中可能出现相邻字母连笔的情况。0为不连笔;1为默认连笔,也是默认值;2在ios 上不支持。
    
    
    NSString *const NSKernAttributeName;//值为浮点数NSNumber,字距属性,默认值为0。
    
    
    NSString *const NSStrikethroughStyleAttributeName;//值为整型NSNumber,可取值为
    
    
    enum {
    
    
    NSUnderlineStyleNone = 0×00,
    
    
    NSUnderlineStyleSingle = 0×01,
    
    
    };设置删除线。
    
    
    NSString *const NSUnderlineStyleAttributeName;//同上。设置下划线。
    
    
    NSString *const NSStrokeColorAttributeName;//值为UIColor,默认值为nil,设置的属性同ForegroundColor。
    
    
    NSString *const NSStrokeWidthAttributeName;//值为浮点数NSNumber。设置比画的粗细。
    
    
    NSString *const NSShadowAttributeName;//值为NSShadow,设置比画的阴影,默认值为nil。
    
    
    NSString *const NSVerticalGlyphFormAttributeName;//值为整型NSNumber,0为水平排版的字,1为垂直排版的字。
  • 相关阅读:
    Struts整合Spring3时注意
    Android组件通讯之BroadcastReceiver应用闹钟服务
    Android组件通讯之Pending Intent与Notification
    Android组件通讯之Service的基础绑定
    Android网络编程之Web Service初步(服务器端搭建)
    Android数据存储之ContentProvider调用联系人数据
    Android网络编程之Socket方式上传对象序列化文件(服务器端)
    Android组件通讯之可跨进程的远程Service调用
    Android网络编程之Web Service初步(客户端)
    Android网络编程之Socket方式上传对象序列化文件(客户端)
  • 原文地址:https://www.cnblogs.com/niit-soft-518/p/4501107.html
Copyright © 2020-2023  润新知