在 swift 的 UIButton 中将标题标签中的特定单词加粗?
Making specific words in a title label bold in a UIButton in swift?
我是 swift 的初学者,我发现 this Whosebug question and 对我的案例没有帮助,很可能是因为我的编码方式与他们不同(即 Swift, 不是 Obc).
private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setTitle("dont have an account? sign up!", for: .normal) //line 4
return button
我想要文字“注册!”在第 4 行中以粗体显示格式,但尚未在网上找到任何可以支持我当前编码方式的内容。
使用按钮 setAttributedTitle
属性 设置属性文本。
首先,创建属性文本。
在这里,我为粗体属性文本创建了一个字符串扩展。 return 属性文本并将此属性文本设置为按钮。
extension String {
/// Return attributed string
/// - Parameter text: String text for bold text.
func getAttributedBoldText(text: String) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self, attributes: [.foregroundColor: UIColor.blue])
if let range = self.range(of: text) {
let startIndex = self.distance(from: self.startIndex, to: range.lowerBound)
let range = NSMakeRange(startIndex, text.count)
attributedString.addAttributes([.font : UIFont.boldSystemFont(ofSize: 20)], range: range)
}
return attributedString
}
}
用法:
private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setAttributedTitle("dont have an account? sign up!".getAttributedBoldText(text: "sign up!"), for: .normal) // Here
return button
}()
注意:根据您的布局修改扩展属性函数。
我是 swift 的初学者,我发现 this Whosebug question and
private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setTitle("dont have an account? sign up!", for: .normal) //line 4
return button
我想要文字“注册!”在第 4 行中以粗体显示格式,但尚未在网上找到任何可以支持我当前编码方式的内容。
使用按钮 setAttributedTitle
属性 设置属性文本。
首先,创建属性文本。
在这里,我为粗体属性文本创建了一个字符串扩展。 return 属性文本并将此属性文本设置为按钮。
extension String {
/// Return attributed string
/// - Parameter text: String text for bold text.
func getAttributedBoldText(text: String) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self, attributes: [.foregroundColor: UIColor.blue])
if let range = self.range(of: text) {
let startIndex = self.distance(from: self.startIndex, to: range.lowerBound)
let range = NSMakeRange(startIndex, text.count)
attributedString.addAttributes([.font : UIFont.boldSystemFont(ofSize: 20)], range: range)
}
return attributedString
}
}
用法:
private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setAttributedTitle("dont have an account? sign up!".getAttributedBoldText(text: "sign up!"), for: .normal) // Here
return button
}()
注意:根据您的布局修改扩展属性函数。