extension String {
func accentTagAndLink(tags:Array<String>) -> NSMutableAttributedString {
let attributedString:NSMutableAttributedString = NSMutableAttributedString(string: self)
var NSContents = self as NSString
for tagChild in tags {
if !tagChild.starts(with: "<") {
let range = NSContents.range(of: "#" + tagChild)
var changeString = ""
for _ in 0..<tagChild.count {
changeString += "$"
}
NSContents = NSContents.replacingOccurrences(of: tagChild, with: changeString, options: .literal, range: range) as NSString
attributedString.addAttribute(.link, value: tagChild, range: range)
attributedString.addAttribute(.foregroundColor, value: UIColor(red: 79/255, green: 205/255, blue: 255/255, alpha: 1), range: range)
}
}
return attributedString
}
}
tableviewCell
class PostCell: TableViewCell {
@IBOutlet weak var postContent: UITextView!
}
在mainViewController中
class PostViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UITextViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = postTableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let post = postList[indexPath.row]
let tags = (post["Content"] as! String).FindTagAtString()
cell.postContent.delegate = self
cell.postContent.isSelectable = true
cell.postContent.isEditable = false
cell.postContent.dataDetectorTypes = UIDataDetectorTypes.link
cell.postContent.attributedText = (post["Content"] as! String).accentTagAndLink(tags: tags)
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print("link")
return true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("cell")
}
}
{{1}中NSLink
中的UITextView
我想点击链接事件返回“链接”
但只能调用TableViewCell
Tab事件
总是返回“单元格”
告诉我们如何使用这个我不知道
TableViewCell
有效,但我的代码崩溃了
让它成为自拍链接
AttributedString的用法是否错误?
帮助
答案 0 :(得分:1)
仅当文本视图是可选的但不可编辑时,文本视图中的链接才是交互式的。也就是说,如果UITextView的值的selectable属性为YES和isEditable属性为NO。
我认为您忘记将NUM1
设置为false。
Apple Doc