gpt4 book ai didi

Swift UIText View 替换字符越界

转载 作者:行者123 更新时间:2023-11-30 11:21:19 27 4
gpt4 key购买 nike

我尝试替换图像链接并显示在 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)

如何解决这个问题?

最佳答案

事情是:你正在改变这一行中的attributedString

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

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

关于Swift UIText View 替换字符越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51241710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com