ios - 替换 NSAttributedString 上的字符时发生崩溃

标签 ios swift cocoa-touch foundation

知道为什么会崩溃:

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/

相关文章:

ios - 如何在 UITableView Cell 中实现类似 iOS Mail 的从左向右滑动

ios - 与包含它们的字符集相比,只有 2 个表情符号返回不正确的长度

swift - 'RLMException',原因 : 'Opening Realm files of format version 11 is not supported by this version of Realm'

objective-c - 在 viewDidUnload() 中设置为 nil

ios scheduledTimerWithTimeInterval 时间量

iOS - 是否可以使用其展开操作方法中的代码中止展开转场?

ios - 为现有的 objective c + swift 项目添加单元测试

ios - 将 Xcode 11 testresult .xcresult 转换为 JUnit?

iphone - 如何绘制填充多边形?

iphone - iPhone 或 iPod Touch 可以与同一房间内的其他设备通信吗?