使用 Swift 制作可点击的 UILabel

Make Clickable UILabel Using Swift

我想使用 Swift 在 UILabel 文本中设置可单击的特定单词。

可能吗?

如果此处有多个标签,我如何检测按下了哪个字词?

你不能用简单的标签来做。

github 中有可用的库。

https://github.com/TTTAttributedLabel/TTTAttributedLabel

由此您可以使用名为 yourLabel.addLinkToURL()

的方法
class ViewController: UIViewController , TTTAttributedLabelDelegate{

    @IBOutlet var lbl: TTTAttributedLabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        var str : NSString = "Hello this is link"
        lbl.delegate = self
        lbl.text = str as String
        var range : NSRange = str.rangeOfString("link")
        lbl.addLinkToURL(NSURL(string: "http://github.com/mattt/")!, withRange: range)
    }

    func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
        UIApplication.sharedApplication().openURL(url)
    }
}

SWIFT 3.0

    privacyLabel.delegate = self
    let strPolicy  : NSString = "Agree to the Terms & Conditions"
    privacyLabel.text = strPolicy as String
    let range1 : NSRange = strPolicy.range(of: "Terms & Conditions")
    privacyLabel.addLink(to: URL(string: "http://Terms.com")!, with: range1)



    func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {

         print("url \(url)")
          // UIApplication.sharedApplication().openURL(url)
    }

我想分享我的图书馆https://github.com/psharanda/Atributika

它包含 TTTAtributedLabel 的现代替代品 + 一套强大的方法来检测和设计不同的东西,如标签、主题标签、提及等(所有这些都可以点击)

一些代码来展示它是如何工作的:

    let link = Style
        .font(.boldSystemFont(ofSize: 14))
        .foregroundColor(.black)
        .foregroundColor(.red, .highlighted)

    let tos = link.named("tos")
    let pp = link.named("pp")

    let all = Style
        .font(.systemFont(ofSize: 14))
        .foregroundColor(.gray)

    let text = "<tos>Terms of Service</tos> and <pp>Privacy Policy</pp>"
        .style(tags: tos, pp)
        .styleAll(all)

    let tosLabel = AttributedLabel()
    tosLabel.textAlignment = .center
    tosLabel.attributedText = text
    tosLabel.onClick = { label, detection in
        switch detection.type {
        case .tag(let tag):
            switch tag.name {
            case "pp":
                print("Privacy Policy clicked")
            case "tos":
                print("Terms of Service clicked")
            default:
                break
            }
        default:
            break
        }
    }

    view.addSubview(tosLabel)