简体   繁体   English

如何在Swift 3的UILabel中使主题标签可单击?

[英]how can I make hashtags clickable in UILabel in Swift 3?

In my application I created an extension to UILabel that contains the following method: 在我的应用程序中,我创建了UILabel的扩展,其中包含以下方法:

func formatTextInLabel() {
    let text = self.text
    let font = UIFont(name: fontName, size: 16.0)
    let titleDict: NSDictionary = [NSFontAttributeName: font!]
    // This will give me an attributedString with the desired font
    let attributedString = NSMutableAttributedString(string: text!, attributes: titleDict as! [String : AnyObject])
    let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
    let matches = regex!.matches(in: text!, options: [], range: NSMakeRange(0, text!.characters.count))
    for match in matches {
        let matchRange = match.rangeAt(0)

        let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor]

        attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange)
    }
    self.attributedText = attributedString
}

and it highlights all #hashtags in my chosen color. 并以我选择的颜色突出显示所有#hashtags But they are not clickable, I found some post on SO that says it's impossible to achieve: How to detect and make hyperlinks/mentions/hashtags clickable in UILabel? 但是它们不是可点击的,我在SO上发现了一些帖子说这是不可能实现的: 如何检测UILabel中的可点击超链接/提及/标签? but it seems to be outdated (hopefully). 但它似乎已经过时了(希望如此)。 Can you give me a hint how can I eg display in the console the name of selected hashtag? 您能否给我一个提示,例如如何在控制台中显示所选主题标签的名称?

One more thing to add - I'm aware of some pod s like ActiveLabel or similar, but I tried them and had problems with constraints in my case, so I want to achieve this effect from my own code. 要添加的另一件事-我知道一些类似ActiveLabel或类似的pod ,但是我尝试了它们,并遇到了约束方面的问题,因此我想通过自己的代码实现这种效果。

Try adding a UITapGestureRecognizer to the label: 尝试将UITapGestureRecognizer添加到标签:

let tap = UITapGestureRecognizer(target: self, action: #selector(handleLabelTap(_:)))
label.addGestureRecognizer(tap)

func handleLabelTap(_ sender: UITapGestureRecognizer) {

    // Do something here for when the user taps on the label

}

For that to work, you probably have to set isUserInteractionEnabled to true on for the label. 为此,您可能必须将isUserInteractionEnabled设置为true才能使用标签。 I just did a test in Xcode and it worked. 我只是在Xcode中进行了测试,所以效果很好。 So: 所以:

label.isUserInteractionEnabled = true

EDIT: 编辑:

If you want to determine which hashtag has been tapped, at the top of your class declaration, before it's initialized create properties for an empty UILabel array, and an empty UITapGestureRecognizer array like this: 如果要确定已挖掘的主题标签,请在类声明的顶部,在初始化之前,为一个空的UILabel数组和一个空的UITapGestureRecognizer数组创建属性,如下所示:

var labels:[UILabel] = [UILabel]()
var labelTaps:[UITapGestureRecognizer] = [UITapGestureRecognizer]()

Then when you create each label append the label and the tap gesture to each respective array 然后,当您创建每个标签时,将标签和点击手势分别添加到每个数组中

let label = UILabel()
// Set all label properties as you wish

// Make sure to add
label.isUserInteractionEnabled = true

// Create the tap gesture
let tap = UITapGestureRecognizer(target: self, action: #selector(handleLabelTap(_:)))
label.addGestureRecognizer(tap)

labels.append(label)
labelTaps.append(tap)

Then when a user taps on one of the hash-tags, you can get the index of which tap gesture was sent to the method, and then use that to figure out which label it is because it would have the same index in the 'labels' array as it's respective gesture recognizer would have in the 'labelTaps' array. 然后,当用户点击一个哈希标签时,您可以获取向该方法发送了点击手势的索引,然后使用该索引来找出它是哪个标签,因为它在“标签”中具有相同的索引'数组,因为其各自的手势识别器将在'labelTaps'数组中具有。 Here is how you do that: 这是您的操作方式:

func handleLabelTap(_ sender: UITapGestureRecognizer) {

    if let index = labelTaps.index(of: sender) {

        let tappedLabel:UILabel = labels[index]

        // Now you can do whatever you want
        print("User tapped label with hash-tag: \(tappedLabel.text)")

    }

}

You can't make links clickable in a UILabel , but you can in a UITextField or UITextView . 您不能在UILabel中使链接可单击,但可以在UITextFieldUITextView中使链接可单击。 Those allow adding clickable links. 这些允许添加可点击的链接。

If the link is displayed as a link, like http://address@domain.com then you can simply turn on link detection. 如果该链接显示为链接,例如http://address@domain.com,则您只需打开链接检测即可。 If you want the link to display an arbitrary string like "click here" and make that string clickable you'll need to install an attributed string into the text field/text view. 如果您希望链接显示任意字符串(如“单击此处”)并使该字符串可点击,则需要在文本字段/文本视图中安装属性字符串。

What type of links are these, and what do you want it to look like in the text? 这些是什么类型的链接,您希望它在文本中显示为什么样?

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

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