【问题标题】:Crash replacing characters on NSAttributedString替换 NSAttributedString 上的字符时崩溃
【发布时间】:2017-08-30 05:03:50
【问题描述】:

知道为什么会崩溃:

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:) 中复制代码。

【问题讨论】:

  • 应用崩溃时收到什么消息??
  • 内存访问错误

标签: ios swift cocoa-touch foundation


【解决方案1】:

试试这个:

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

注意:请根据您的要求字符串 addAttribute

【讨论】:

  • 但我需要更改NSAttributedString 中的字符串,而不是向String 添加新属性。
  • 试过什么?即使你的方法有效,也不是我需要的。
【解决方案2】:

试试这个,对你有帮助

斯威夫特 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!)

    }

【讨论】:

  • 这与我的第二种方法相同,我知道它有效。
猜你喜欢
  • 2018-02-13
  • 2023-03-04
  • 2012-01-04
  • 2020-04-21
  • 2023-03-23
  • 2021-11-19
  • 2011-10-11
  • 1970-01-01
  • 2014-12-06
相关资源
最近更新 更多