Swift UIText View replaceCharacters超出范围

时间:2018-07-09 09:01:41

标签: swift uitextview nsattributedstring

我尝试替换图像的链接并在TextView上显示

这是我的代码

class ViewController: UIViewController {

    let textView: UITextView = {
        let view = UITextView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(textView)
        textView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
        let input = "New iPhone \nhttp://cdn2.gsmarena.com/vv/bigpic/apple-iphone-6s1.jpg \nTest Test Test"
        imageText(text: input)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imageText(text:String) {
        let attributedString = NSMutableAttributedString(string: text)
        let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
        let matches = detector?.matches(in: text, options: .reportCompletion, range:NSRange(location: 0, length: text.count))
        for match in matches! {
            if match.url?.absoluteString.suffix(3) == "jpg" {
                let textAttachment = NSTextAttachment()
                let data = NSData(contentsOf: (match.url!))
                if data != nil{
                    let image = UIImage(data: data! as Data)
                    textAttachment.image = image
                    let attributedStringWithImage = NSAttributedString(attachment: textAttachment)
                    attributedString.replaceCharacters(in: (match.range), with: attributedStringWithImage)
                }
            }
        }
        textView.attributedText = attributedString
    }
}

有效:

App Screen Shot

但是,如果我添加第二个链接,则会崩溃。

let input = "New iPhone \nhttp://cdn2.gsmarena.com/vv/bigpic/apple-iphone-6s1.jpg \nTest Test Test \nhttp://cdn2.gsmarena.com/vv/bigpic/apple-iphone-6s1.jpg \nTest Test Test"

控制台

reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'

我发现崩溃点是这条线

attributedString.replaceCharacters(in: (match.range), with: attributedStringWithImage)

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

问题是:您正在此行对attributedString进行突变

attributedString.replaceCharacters(in: (match.range), with: attributedStringWithImage)

因此,在for循环的以下迭代中,您要替换的范围不再存在。