通常我在界面生成器中构建应用程序界面。有时设计需要使用属性字符串(字体、颜色等)。如果字符串是静态的,配置起来很容易。
但是,如果字符串是动态的(带参数的格式),则无法在界面构建器中配置属性。需要写很多代码。
我正在为 NSAttributedString
寻找一些 [NSString stringWithFormat:]
的类似物。所以我将能够在界面生成器中设置字符串格式和必要的属性,然后在代码中提供必要的参数。
例如:
让我们考虑一下我需要这样格式的显示字符串:“%d + %d = %d”(所有数字都是粗体)。< br/>
我想在界面生成器中配置这种格式。在代码中,我想提供参数:1、1、2。应用程序应显示“1 + 1 = 2”。
最佳答案
兼容 Swift 4.2
public extension NSAttributedString {
convenience init(format: NSAttributedString, args: NSAttributedString...) {
let mutableNSAttributedString = NSMutableAttributedString(attributedString: format)
args.forEach { (attributedString) in
let range = NSString(string: mutableNSAttributedString.string).range(of: "%@")
mutableNSAttributedString.replaceCharacters(in: range, with: attributedString)
}
self.init(attributedString: mutableNSAttributedString)
}
}
用法:
let content = NSAttributedString(string: "The quick brown %@ jumps over the lazy %@")
let fox = NSAttributedString(string: "fox", attributes: [.font: Fonts.CalibreReact.boldItalic.font(size: 40)])
let dog = NSAttributedString(string: "dog", attributes: [.font: Fonts.CalibreReact.lightItalic.font(size: 11)])
attributedLabel.attributedText = NSAttributedString(format: content, args: fox, dog)
结果:
关于ios - 是否有 [NSString stringWithFormat :] for NSAttributedString 的任何类似物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31524874/