接 UI-1 那篇
NSAttributedString类可以对字符串附加格式信息
添加字体类型
@IBAction func buttonPressed(_ sender: UIButton) {
let title=sender.title(for: .normal)!
let plainText="\(title) button pressed"
// statusLabel.text=plainText
//用 styleText 实例化一个NSAttributedString的对象
let styleText=NSMutableAttributedString(string:plainText)
//用attributes保存 boldSystemFont 字体的键值,字体大小为标签字体大小
let attributes=[NSFontAttributeName:UIFont.boldSystemFont(ofSize: statusLabel.font.pointSize)]
//获取 title 的 NSRange
let nameRange=(plainText as NSString).range(of: title)
//将 nameRange范围的字改变字体属性,属性可以通过attributes保存 boldSystemFont 字体的键值来找到
styleText.setAttributes(attributes, range: nameRange)
statusLabel.attributedText=styleText
}
}
可以看到指定部分字体变大

网友评论