使用Swift制作可点击的UILabel

时间:2015-08-14 12:29:45

标签: ios swift uilabel

我想使用Swift在UILabel文本中设置特定Word可点击。

有可能吗?

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

3 个答案:

答案 0 :(得分:19)

您无法使用简单标签。

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

enter image description here

答案 1 :(得分:1)

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

答案 2 :(得分:1)

我想分享我的图书馆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)