zoukankan      html  css  js  c++  java
  • 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为垂直排版的字。
  • 相关阅读:
    rapidjson 使用
    【设计模式】模板方法模式
    【设计模式】策略模式
    【设计模式】建造者模式
    【设计模式】享元模式
    /dev/sda1 contains a file system with errors,check forced.
    如何编写高效的Python的代码
    VsCode 调试 Python 代码
    Python 使用 pyinstaller 打包 代码
    初次使用git上传代码到github远程仓库
  • 原文地址:https://www.cnblogs.com/niit-soft-518/p/4501107.html
Copyright © 2011-2022 走看看