简体   繁体   中英

how to create tappable text in uitextview in swift

我想在点击这些文本时创建可点击的文本,然后执行一些操作,例如调用任何函数对该文本进行某些操作,我会在不是整个uitextview上的任何文本上进行抓取

If I understand your question correctly, you want to click on a text view and call a function. You can use UITapGestureRecognizer.

@IBOutlet weak var textView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.isUserInteractionEnabled = true
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelTapped))
        textView.addGestureRecognizer(tapGestureRecognizer)

    }

    @objc func labelTapped(){
        print("Do something")
    }

Try this -

override func viewDidLoad() {
    super.viewDidLoad()

    // You must set the formatting of the link manually
    let linkAttributes: [NSAttributedStringKey: Any] = [
        .link: NSURL(string: "https://www.apple.com")!,
        .foregroundColor: UIColor.blue
    ]

    let attributedString = NSMutableAttributedString(string: "Just click here to register")

    // Set the 'click here' substring to be the link
    attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10))

    self.textView.delegate = self
    self.textView.attributedText = attributedString
    self.textView.isUserInteractionEnabled = true
    self.textView.isEditable = false
}

I've faced with problem same like your and I've tried many things to resolve. The best approach will be use Atributika (or similar) library. You will not regret this decision. It's easy to use and have a lot features.

https://github.com/psharanda/Atributika

If I understand your question properly then you could just add a button then change the button text to the text you want. Then like normal text you can mess with the colour, border or fill. After you have added this to your app link it up as an action with your view controller.swift file

Here is an example from my app 'Health Dash':

Image 1

Image 2

Then the swift 4 code:

import UIKit

class FriendsViewController: UIViewController {
 @IBAction func exampleText(_ sender: Any) {
     print("When you click this button something happens")
 }

 override func viewDidLoad() {
     super.viewDidLoad()

     // Do any additional setup after loading the view.
 }
}

Here is an image of what it should look like:

Image 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM