简体   繁体   中英

Crash replacing characters on NSAttributedString

Any idea why this crashes:

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: "-")

But this doesn't?

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: all I did on the second gist was copy the code from inside the replaceCharacters(inRange:withString:) from the first gist.

Try this:

 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

Try this, This will help you

Swift 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!)

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM