【swift】NSMutableAttributedString的使用

本文介绍了如何使用NSMutableAttributedString来设置UILabel的文字属性,包括字体大小和颜色,并提供了具体的Swift代码实现方法。

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

使用步骤

  1. NSMutableAttributedString初始化
  2. 引用方法
  3. 给label等赋值(attributedText)

封装方法

//传入字符串、字体      返回NSMutableAttributedString
private func appendStrWithString(str:String,font:CGFloat) -> NSMutableAttributedString {
    var attributedString : NSMutableAttributedString
    let attStr = NSMutableAttributedString.init(string: str, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(font)])
    attributedString = NSMutableAttributedString.init(attributedString: attStr)
    return attributedString
}

//传入字符串、字体、颜色      返回NSMutableAttributedString
private func appendColorStrWithString(str:String,font:CGFloat,color:UIColor) -> NSMutableAttributedString {
    var attributedString : NSMutableAttributedString
    let attStr = NSMutableAttributedString.init(string: str, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(font),NSForegroundColorAttributeName:color])
    attributedString = NSMutableAttributedString.init(attributedString: attStr)
    return attributedString
}

引用方法

                    let attributedString = NSMutableAttributedString.init()//初始化

                    let needIntegral = json["NeedIntegral"].intValue//还需要多少积分才能领取              
                     attributedString.appendAttributedString(self.appendColorStrWithString("您还需要", font: 14, color: UIColor.init(102, 102, 102)))//调用方法 
                    attributedString.appendAttributedString(self.appendColorStrWithString("\(needIntegral)", font: 14, color: UIColor.init(223, 51, 72)))
                    attributedString.appendAttributedString(self.appendColorStrWithString("积分才能兑换该商品", font: 14, color: UIColor.init(102, 102, 102)))

                    self.alertContentLabel.attributedText = attributedString//赋值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值