NSMutableAttributedString 与UILabel 常用使用

本文详细介绍了如何在 iOS 开发中利用 NSMutableAttributedString 实现字符串文本的字体颜色和大小设置,并通过实例展示了如何将样式化的文本关联到 UILabel 组件上,包括设置字体颜色、大小以及与其他 UI 元素的关联。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 第一步:NSMutableAttributedString与NSString关联

NSString *pingguString = [NSStringstringWithFormat:@"%@%@",pingguString1,pingguString2];

NSMutableAttributedString *str = [[NSMutableAttributedStringalloc] initWithString:pingguString];

 第二步:设置字体颜色和大小  (NSForegroundColorAttributeName和NSFontAttributeName只支持ios6以上)

    [str addAttribute:NSForegroundColorAttributeNamevalue:(id)[UIColorredColor].CGColorrange:NSMakeRange(0, pingguString1.length)];

    [str addAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:13]range:NSMakeRange(0, pingguString1.length)];

    [str addAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor] range:NSMakeRange(pingguString1.length, pingguString2.length)];

    [str addAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:13]range:NSMakeRange(pingguString1.length, pingguString2.length)];

第三步:NSMutableAttributedString与UILabel关联

    UILabel * label = [[UILabelalloc] initWithFrame:rect];

    [label setFont:[UIFontsystemFontOfSize:fonSize]];

    [label setBackgroundColor:Color];

    [label setTextAlignment:alignment];

    [label setNumberOfLines:2];

    [label setTag:tag];

    [label setLineBreakMode:UILineBreakModeWordWrap];

    label.attributedText = str;

    [self.contentViewaddSubview:label];

    [str release];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值