简体   繁体   English

如何在uitextview中快速创建可点击文本

[英]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. 您可以使用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. 最好的方法是使用Atributika(或类似的库)。 You will not regret this decision. 您不会后悔这一决定。 It's easy to use and have a lot features. 它易于使用并且具有很多功能。

https://github.com/psharanda/Atributika 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 将其添加到应用程序后,将其链接为与View controller.swift文件的操作

Here is an example from my app 'Health Dash': 这是我的应用程序“ Health Dash”中的一个示例:

Image 1 图片1

Image 2 图片2

Then the swift 4 code: 然后是迅速的4代码:

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 图片3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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