How can I accurately detect if a link is clicked inside UILabels in Swift 4?

后端 未结 6 1071
暗喜
暗喜 2021-02-07 12:24

Edit

See my answer for a full working solution:

I managed to solve this myself by using a UITextView instead of a UILabel

6条回答
  •  心在旅途
    2021-02-07 12:31

    You can use MLLabel library. MLLabel is a subclass of UIlabel. The library has a class MLLinkLabel that is subclass of MLLabel. That means you can use it in place of UIlabel (even in interface builder just drag a UILabel and change it's class to MLLinkLabel)

    MLLinkLabel can do the trick for you and it is very easy. Here is an example:

        label.didClickLinkBlock = {(link, linkText, label) -> Void in
    
            //Here you can check the type of the link and do whatever you want.
            switch link!.linkType {
            case .email:
                break
            case .none:
                 break
            case .URL:
                 break
            case .phoneNumber:
                 break
            case .userHandle:
                 break
            case .hashtag:
                 break
            case .other:
                 break
            }
    
        }
    

    you can check the library in GitHub https://github.com/molon/MLLabel

    Here is a screenshot from one of my apps that I used MLLabel in it.

提交回复
热议问题