扩展代码:
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
}
}
表视图单元:
class PostCell: TableViewCell {
@IBOutlet weak var postContent: UITextView!
}
在主视图控制器中
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.isUserInteractionEnabled = true
cell.postContent.dataDetectorTypes = UIDataDetectorTypes.link
cell.postContent.attributedText = (post["Content"] as! String).accentTagAndLink(tags: tags)
let tap = MyTapGesture(target: self, action: #selector(self.tapTextView))
tap.indexPath = indexPath
cell.postContent.addGestureRecognizer(tap)
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print(URL)
return true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("cell tap")
movePostDetail(indexPath)
}
@objc func tapTextView(sender:MyTapGesture){
print("cell tap")
movePostDetail(sender.indexPath)
}
}
MyTapGesture:
class MyTapGesture: UITapGestureRecognizer {
var indexPath:IndexPath!
}
内容是NormalText + TagText
如果点击 NormalText 运行 movePostDetail 并且如果点击 TagText 运行 print(URL) 但总是 movePostDetail 时addGestureRecognizer
如何一起使用
拍的时候效果很好TTTAttributedLabel
,但是因为崩溃所以没用过TTTAttributedLabel
。