崩溃替换NSAttributedString上的字符

时间:2017-08-30 05:03:50

标签: 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:)内部的代码。

2 个答案:

答案 0 :(得分:0)

试试这个:

'
  

注意:请根据您的要求添加String addAttribute

答案 1 :(得分:0)

试试这个,这会对你有帮助

斯威夫特3:

 let label = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()

        let attrString = NSMutableAttributedString(string: "abcdef")
        attrString.mutableString.replaceCharacters(in: NSRange(location: 1, length: 1), with: "-")

        label.attributedText = NSAttributedString(string: attrString.string)
        print(label.attributedText!)

    }