NSString 属性更改合集

本文介绍如何使用NSAttributedString对UILabel进行字体样式的调整,包括更改行距、字体颜色、大小、描边等,并提供了一些示例代码。

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

前言

我们经常碰到更改UILabel等控件字体样式,像更改行距,个别字体变色,个别字体变大,字体加边框等,这里将碰到的一些情况进行总结。

所有的Key

NSFontAttributeName; //字体,value是UIFont对象
NSParagraphStyleAttributeName;//绘图的风格(居中,换行模式,间距等诸多风格),value是NSParagraphStyle对象
NSForegroundColorAttributeName;// 文字颜色,value是UIFont对象
NSBackgroundColorAttributeName;// 背景色,value是UIFont
NSLigatureAttributeName; //  字符连体,value是NSNumber
NSKernAttributeName; // 字符间隔
NSStrikethroughStyleAttributeName;//删除线,value是NSNumber
NSUnderlineStyleAttributeName;//下划线,value是NSNumber
NSStrokeColorAttributeName; //描绘边颜色,value是UIColor
NSStrokeWidthAttributeName; //描边宽度,value是NSNumber
NSShadowAttributeName; //阴影,value是NSShadow对象
NSTextEffectAttributeName; //文字效果,value是NSString
NSAttachmentAttributeName;//附属,value是NSTextAttachment 对象
NSLinkAttributeName;//链接,value是NSURL or NSString
NSBaselineOffsetAttributeName;//基础偏移量,value是NSNumber对象
NSUnderlineColorAttributeName;//下划线颜色,value是UIColor对象
NSStrikethroughColorAttributeName;//删除线颜色,value是UIColor
NSObliquenessAttributeName; //字体倾斜
NSExpansionAttributeName; //字体扁平化
NSVerticalGlyphFormAttributeName;//垂直或者水平,value是 NSNumber0表示水平,1垂直

常用设置

//创建字典存储属性
 NSMutableDictionary *attributes = [NSMutableDictionary dictionary];

//1.更改大小
    [attributes setValue:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];
//2.字体颜色
  [attributes setValue:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];   
//3.背景色 
  [attributes setValue:[UIColor grayColor] forKey:NSBackgroundColorAttributeName]; 

//4.设置描边
   [attributes setValue:[UIColor grayColor] forKey:NSStrokeColorAttributeName];
    [attributes setValue:@(2.0) forKey:NSStrokeWidthAttributeName];

//添加到string上
 NSAttributedString *attri = [[NSAttributedString alloc] initWithString:string attributes:attributes];

//用法
label.attributedText = attri;

//第二种简单写法

//简易写法
   NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    [attributeString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSBackgroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, attributeString.length)];
//用法
label.attributedText = attributeString;  

更多用法参考:http://blog.youkuaiyun.com/hello_hwc/article/details/46731991

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值