SwiftiOS如何同时使用UITableView和NSLink?
How to use UITableView and NSLink together in Swift iOS?
分机号:[=39=]
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!
}
在 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.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 when addGestureRecognizer
如何搭配使用
我用TTTAttributedLabel
的时候很好用,但是因为崩溃所以没用TTTAttributedLabel
。
我建议您使用自定义属性名称并自行处理窃听。
Swift 4
中的解决方案
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapGes = UITapGestureRecognizer(target: self, action: #selector(TableViewCell.handleTap(sender:)))
contentTf.addGestureRecognizer(tapGes)
let attributeName = "CustomAttributeName"
let attStr = NSAttributedString(string: "https", attributes: [NSAttributedStringKey(rawValue: attributeName):"https"])
contentTf.attributedText = attStr
}
@objc func handleTap(sender: UITapGestureRecognizer) -> Void {
let myTextView = sender.view as! UITextView
let layoutManager = myTextView.layoutManager
// location of tap in myTextView coordinates and taking the inset into account
var location = sender.location(in: myTextView)
location.x -= myTextView.textContainerInset.left;
location.y -= myTextView.textContainerInset.top;
// character index at tap location
let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
// if index is valid then do something.
if characterIndex < myTextView.textStorage.length {
// print the character index
print("character index: \(characterIndex)")
// print the character at the index
let myRange = NSRange(location: characterIndex, length: 1)
let substring = (myTextView.attributedText.string as NSString).substring(with: myRange)
print("character at index: \(substring)")
// check if the tap location has a certain attribute
let attributeName = "CustomAttributeName"
let attributeValue = myTextView.attributedText.attribute(NSAttributedStringKey(rawValue: attributeName), at: characterIndex, effectiveRange: nil) as? String
if let value = attributeValue {
print("You tapped on \(attributeName) and the value is: \(value)")
}
}
}
测试
character index: 3
character at index: p
You tapped on CustomAttributeName and the value is: https
分机号:[=39=]
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!
}
在 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.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 when addGestureRecognizer
如何搭配使用
我用TTTAttributedLabel
的时候很好用,但是因为崩溃所以没用TTTAttributedLabel
。
我建议您使用自定义属性名称并自行处理窃听。
Swift 4
中的解决方案override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapGes = UITapGestureRecognizer(target: self, action: #selector(TableViewCell.handleTap(sender:)))
contentTf.addGestureRecognizer(tapGes)
let attributeName = "CustomAttributeName"
let attStr = NSAttributedString(string: "https", attributes: [NSAttributedStringKey(rawValue: attributeName):"https"])
contentTf.attributedText = attStr
}
@objc func handleTap(sender: UITapGestureRecognizer) -> Void {
let myTextView = sender.view as! UITextView
let layoutManager = myTextView.layoutManager
// location of tap in myTextView coordinates and taking the inset into account
var location = sender.location(in: myTextView)
location.x -= myTextView.textContainerInset.left;
location.y -= myTextView.textContainerInset.top;
// character index at tap location
let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
// if index is valid then do something.
if characterIndex < myTextView.textStorage.length {
// print the character index
print("character index: \(characterIndex)")
// print the character at the index
let myRange = NSRange(location: characterIndex, length: 1)
let substring = (myTextView.attributedText.string as NSString).substring(with: myRange)
print("character at index: \(substring)")
// check if the tap location has a certain attribute
let attributeName = "CustomAttributeName"
let attributeValue = myTextView.attributedText.attribute(NSAttributedStringKey(rawValue: attributeName), at: characterIndex, effectiveRange: nil) as? String
if let value = attributeValue {
print("You tapped on \(attributeName) and the value is: \(value)")
}
}
}
测试
character index: 3
character at index: p
You tapped on CustomAttributeName and the value is: https