簡體   English   中英

如何在uitextview中快速創建可點擊文本

[英]how to create tappable text in uitextview in swift

我想在點擊這些文本時創建可點擊的文本,然后執行一些操作,例如調用任何函數對該文本進行某些操作,我會在不是整個uitextview上的任何文本上進行抓取

如果我正確理解了您的問題,則需要單擊文本視圖並調用一個函數。 您可以使用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")
    }

嘗試這個 -

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
}

我遇到了類似您的問題,並且嘗試了很多方法來解決。 最好的方法是使用Atributika(或類似的庫)。 您不會后悔這一決定。 它易於使用並且具有很多功能。

https://github.com/psharanda/Atributika

如果我正確理解您的問題,那么您可以添加一個按鈕,然后將按鈕文本更改為所需的文本。 然后像普通文本一樣,您可能會弄亂顏色,邊框或填充。 將其添加到應用程序后,將其鏈接為與View controller.swift文件的操作

這是我的應用程序“ Health Dash”中的一個示例:

圖片1

圖片2

然后是迅速的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.
 }
}

這是它的外觀圖像:

圖片3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM