【发布时间】:2018-07-09 09:01:41
【问题描述】:
我尝试替换图片链接并在 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
}
}
有效:
但如果我添加第二个链接,它就会崩溃。
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)
如何解决这个问题?
【问题讨论】:
-
你需要倒着做。因为如果您更改第一个,那么您的字符串的长度会更小,因为您将长链接更改为小文本附件。忘记图像,假设您将每个链接替换为“Hello”,您就明白了。现在,修复它:
for match in matches!=>for match in matches!.reversed() -
感谢您的回答它有效
标签: swift uitextview nsattributedstring