一个字符串展现多种字体、字号、字体大小(NSAttributedString)

本文介绍了NSAttributedString的使用,通过这种富文本技术,可以轻松在字符串中应用不同的字体、字号和大小,实现文本的多样化展示,同时支持段落格式设置。

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


NSAttributedString叫做富文本,是一种带有属性的字符串,通过它可以轻松的在一个字符串中表现出多种字体、字号、字体大小等各不相同的风格,还可以对段落进行格式化。



   以下是实现代码:

 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 500)];
    label.numberOfLines = 0;//设置段落paragraphStyle,numberOfLines必须为0
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.backgroundColor = [UIColor redColor];
    
    NSString *str1 = @"全球开发者大会(WWDC)";
    NSString *str2 = @"美国在旧金山芳草地";
    NSString *str5 = @"太平洋时间";
    NSString *str3 = @"开始:2016-03-10";
    NSString *str4 = @"结束:2016-03-20";
    NSString *string = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@",str1,str2,str5,str3,str4];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 20.0;
    NSDictionary *attrsDictionary1 = @{NSFontAttributeName:[UIFont systemFontOfSize:30],
                                      NSParagraphStyleAttributeName:paragraphStyle};
    NSDictionary *attrsDictionary2 = @{NSParagraphStyleAttributeName:paragraphStyle};
    //给str1添加属性,字体加粗,并且设置段落间隙
    [attributedString addAttributes:attrsDictionary1 range:NSMakeRange(0, str1.length)];
    //给str2设置段落间隙
    [attributedString addAttributes:attrsDictionary2 range:NSMakeRange(str1.length, str2.length)];
    //attributedString如果还有别的样式需要添加可以这样依次加属性
    label.attributedText = attributedString;
    [self.view addSubview:label];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值