ios富文本属性

本文通过一个详细的实例展示了如何使用NSAttributedString来为iOS应用中的UILabel文本添加多种样式效果,包括加粗、改变颜色、设置背景色、添加下划线及阴影等。

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

@interface ViewController ()@property (weak,nonatomic

IBOutlet UILabel *stringLabel;@end@implementation ViewController

- (void)viewDidLoad {  

[super viewDidLoad];  

NSString *string = _stringLabel.text; //初始化属性字符串  

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; //字体类型属性  

NSDictionary *BoldFontAS = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:17]}; [attributedString addAttributes:BoldFontAS range:[string rangeOfString:@"BoldFont"]]; //字体颜色属性  

NSDictionary *RedFondAS = @{NSForegroundColorAttributeName :[UIColor redColor]};  

[attributedString addAttributes:RedFondAS range:[string rangeOfString:@"RedFont"]]; //字体背景颜色和字体颜色属性 NSDictionary *BuleBackgroundAS = @{NSBackgroundColorAttributeName:[UIColor blueColor], NSForegroundColorAttributeName:[UIColor whiteColor]};  

[attributedString addAttributes:BuleBackgroundAS range:[string rangeOfString:@"BuleBackground"]]; //字体下划线与字体下划线颜色属性  

NSDictionary *UnderlineAS = @{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle],NSUnderlineColorAttributeName:[UIColor greenColor]};  

[attributedString addAttributes:UnderlineAS range:[string rangeOfString:@"Underline"]]; //字体阴影属性  

NSShadow *shadow = [[NSShadow alloc] init];  

shadow.shadowOffset = CGSizeMake(2, 2);  

shadow.shadowColor = [UIColor orangeColor];  

NSDictionary *ShadowAS = @{NSShadowAttributeName:shadow};  

[attributedString addAttributes:ShadowAS range:[string rangeOfString:@"Shadow"]]; //设置Label的字符串属性 _stringLabel.attributedText = attributedString;}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值