知道为什么会崩溃:
extension NSAttributedString {
func replaceCharacters(inRange: NSRange, withString: String) -> NSAttributedString {
let mutableString = mutableCopy() as! NSMutableAttributedString
mutableString.replaceCharacters(in: inRange, with: withString)
return mutableString
}
}
let label = UILabel()
label.attributedText = NSAttributedString(string: "abcdef")
let string = label.attributedText?.replaceCharacters(inRange: NSRange(location: 1, length: 1), withString: "-")
但这不是吗?
let label = UILabel()
label.attributedText = NSAttributedString(string: "abcdef")
let mutableString = label.attributedText?.mutableCopy() as! NSMutableAttributedString
mutableString.replaceCharacters(in: NSRange(location: 1, length: 1), with: "-")
let string: NSAttributedString = mutableString
PS:我在第二个要点上所做的只是从第一个要点的 replaceCharacters(inRange:withString:)
内部复制代码。
最佳答案
试试这个:
extension String {
func replaceCharacters(withString: String) -> NSAttributedString {
var range = (self as NSString).range(of: withString)
let attributedString = NSMutableAttributedString(string:self)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: range)
if let font = UIFont(name: "Helvetica Bold", size: 14) {
attributedString.addAttribute(NSFontAttributeName, value: font, range: range)
}
return attributedString
}
}
let label = UILabel()
label.attributedText = "pqr abcdefg xyz".replaceCharacters("abc")
Note: Please String addAttribute as per your requirement
关于ios - 替换 NSAttributedString 上的字符时发生崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45952262/