设置UILabel上面的文字显示不同的字体和颜色

来源:互联网 发布:手机桌面归类软件 编辑:程序博客网 时间:2024/05/16 05:34

    /**************************************显示内容是英文***********************************************/

    

    // 创建显示英文的Label初始化并确定位置

    UILabel *labelofEN = [[UILabelalloc]initWithFrame:CGRectMake(0,200, [[UIScreenmainScreen]bounds].size.width,100)];

    // 构造字符串

    NSMutableAttributedString *str1 = [[NSMutableAttributedStringalloc]initWithString:@"Hello World China Is Strong"];

    // 为字符串中的字符添加不同的颜色

    [str1 addAttribute:NSForegroundColorAttributeNamevalue:[UIColorblueColor]range:NSMakeRange(0,11)];

    [str1 addAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor]range:NSMakeRange(12,15)];

    // 为字符串中的字符添加不同的字体

    [str1 addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"Arial-BoldItalicMT"size:30.0]range:NSMakeRange(0,11)];

    [str1 addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"HelveticaNeue-Bold"size:30.0]range:NSMakeRange(12,15)];

    // Label的显示内容

    labelofEN.attributedText = str1;

    // Label的内容居中显示

    labelofEN.textAlignment =NSTextAlignmentCenter;

    // 把Label展示到画布上

    [self.viewaddSubview:labelofEN];

  

    

  /**************************************显示内容是中文***********************************************/

    

    // 创建显示中文的Label初始化并确定位置

    UILabel *labelofCH = [[UILabelalloc]initWithFrame:CGRectMake(0,300, [[UIScreenmainScreen]bounds].size.width,100)];

    // 构造字符串

    NSMutableAttributedString *str2 = [[NSMutableAttributedStringalloc]initWithString:@"我爱中国"];

    // 为字符串中的字符添加不同的颜色

    [str2 addAttribute:NSForegroundColorAttributeNamevalue:[UIColorblueColor]range:NSMakeRange(0,1)];

    [str2 addAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor]range:NSMakeRange(1,1)];

    [str2 addAttribute:NSForegroundColorAttributeNamevalue:[UIColorpurpleColor]range:NSMakeRange(2,1)];

    [str2 addAttribute:NSForegroundColorAttributeNamevalue:[UIColororangeColor]range:NSMakeRange(3,1)];

    // 为字符串中的字符添加不同的字体

    [str2 addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"Arial-BoldItalicMT"size:30.0]range:NSMakeRange(0,1)];

    [str2 addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"HelveticaNeue-Bold" size:30.0]range:NSMakeRange(1,1)];

    [str2 addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"Courier-BoldOblique"size:30.0]range:NSMakeRange(2,1)];

    [str2 addAttribute:NSFontAttributeNamevalue:[UIFontfontWithName:@"American Typewriter"size:30.0]range:NSMakeRange(3,1)];

    // Label的显示内容

    labelofCH.attributedText = str2;

    // Label的内容居中显示

    labelofCH.textAlignment =NSTextAlignmentCenter;

    // 把Label展示到画布上

    [self.viewaddSubview:labelofCH];


效果图:



1 0