How to use UITableView and NSLink together in Swift iOS?

Adam

Extension Code:

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!
}

in 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!
}

Content is NormalText + TagText

If tap NormalText to run movePostDetail and if tap TagText to run print(URL) but always movePostDetail when addGestureRecognizer

How to use together

It worked well when I took TTTAttributedLabel, but because of crash so i haven't used TTTAttributedLabel.

potato

I advice you to use a CUSTOM ATTRIBUTE NAME and handle the tap by yourself.

Solution in 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)")
        }

    }
}

TEST

character index: 3
character at index: p
You tapped on CustomAttributeName and the value is: https

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Swift: How to use static cell in dynamic UITableView

From Dev

Swift: How to use static cell in dynamic UITableView

From Dev

How to use Reusable Cells in uitableview for IOS

From Dev

How to use MKSnapshotter in Swift (iOS)

From Dev

iOS UIStepper & NSUserDefaults - How to manage them together and use a double

From Dev

How to create selecting option UITableView similar in iOS Settings in Swift?

From Dev

How to make multiple list in one UITableView? IOS Swift

From Dev

iOS Swift : UITableView KeyPad overlay

From Dev

UITableView with Hierarchical Categories -Swift iOS

From Dev

IOS: how to use UITableView as Newsfeed view for Facebook like application

From Dev

How to create a UITableView in swift

From Dev

how to hide a UITableView in Swift?

From Dev

How to use attributed placeholder in iOS with Swift

From Dev

How to use requestAccessToEntityType method in Swift iOS 8

From Dev

How to use FirebaseUI for Google authentication on iOS in Swift?

From Dev

How to use Cloudmine as API in iOS Swift

From Dev

How to use value of variable in swift iOS

From Dev

Swift/iOS: How to use address (reference, pointer) in swift?

From Dev

Swift/iOS: How to use address (reference, pointer) in swift?

From Java

how to use AppBarConfiguration and setNavigationItemSelectedListener together

From Java

How to use Git and Dropbox together?

From Dev

How to use TortoiseSVN together with Eclipse

From Dev

How to Use MySQL and MongoDb together

From Dev

How to use Resultreceiver and AlarmManager together?

From Dev

How to use completablefuture and Streams together

From Dev

how to use AppBarConfiguration and setNavigationItemSelectedListener together

From Dev

How to use grep and cut together?

From Dev

How to use Resultreceiver and AlarmManager together?

From Dev

How to use || and && together in one if statement

Related Related

  1. 1

    Swift: How to use static cell in dynamic UITableView

  2. 2

    Swift: How to use static cell in dynamic UITableView

  3. 3

    How to use Reusable Cells in uitableview for IOS

  4. 4

    How to use MKSnapshotter in Swift (iOS)

  5. 5

    iOS UIStepper & NSUserDefaults - How to manage them together and use a double

  6. 6

    How to create selecting option UITableView similar in iOS Settings in Swift?

  7. 7

    How to make multiple list in one UITableView? IOS Swift

  8. 8

    iOS Swift : UITableView KeyPad overlay

  9. 9

    UITableView with Hierarchical Categories -Swift iOS

  10. 10

    IOS: how to use UITableView as Newsfeed view for Facebook like application

  11. 11

    How to create a UITableView in swift

  12. 12

    how to hide a UITableView in Swift?

  13. 13

    How to use attributed placeholder in iOS with Swift

  14. 14

    How to use requestAccessToEntityType method in Swift iOS 8

  15. 15

    How to use FirebaseUI for Google authentication on iOS in Swift?

  16. 16

    How to use Cloudmine as API in iOS Swift

  17. 17

    How to use value of variable in swift iOS

  18. 18

    Swift/iOS: How to use address (reference, pointer) in swift?

  19. 19

    Swift/iOS: How to use address (reference, pointer) in swift?

  20. 20

    how to use AppBarConfiguration and setNavigationItemSelectedListener together

  21. 21

    How to use Git and Dropbox together?

  22. 22

    How to use TortoiseSVN together with Eclipse

  23. 23

    How to Use MySQL and MongoDb together

  24. 24

    How to use Resultreceiver and AlarmManager together?

  25. 25

    How to use completablefuture and Streams together

  26. 26

    how to use AppBarConfiguration and setNavigationItemSelectedListener together

  27. 27

    How to use grep and cut together?

  28. 28

    How to use Resultreceiver and AlarmManager together?

  29. 29

    How to use || and && together in one if statement

HotTag

Archive