gpt4 book ai didi

ios - 检测 UILabel 中的点击标签

转载 作者:行者123 更新时间:2023-11-28 06:53:10 25 4
gpt4 key购买 nike

我正在使用此扩展来检测 UILabel 中的标签:

import UIKit

extension UILabel {

func resolveHashTags(){

// turn string in to NSString
let nsText:NSString = self.text!

// this needs to be an array of NSString. String does not work.
let words:[NSString] = nsText.componentsSeparatedByString(" ")

// you can't set the font size in the storyboard anymore, since it gets overridden here.
let attrs = [
NSFontAttributeName : UIFont.systemFontOfSize(17.0)
]

// you can staple URLs onto attributed strings
let attrString = NSMutableAttributedString(string: nsText as String, attributes:attrs)

// tag each word if it has a hashtag
for word in words {

// found a word that is prepended by a hashtag!
// homework for you: implement @mentions here too.
if word.hasPrefix("#") {

// a range is the character position, followed by how many characters are in the word.
// we need this because we staple the "href" to this range.
let matchRange:NSRange = nsText.rangeOfString(word as String)

// convert the word from NSString to String
// this allows us to call "dropFirst" to remove the hashtag
var stringifiedWord:String = word as String

// drop the hashtag
stringifiedWord = String(stringifiedWord.characters.dropFirst())

// check to see if the hashtag has numbers.
// ribl is "#1" shouldn't be considered a hashtag.
let digits = NSCharacterSet.decimalDigitCharacterSet()

if let numbersExist = stringifiedWord.rangeOfCharacterFromSet(digits) {
// hashtag contains a number, like "#1"
// so don't make it clickable
} else {
// set a link for when the user clicks on this word.
// it's not enough to use the word "hash", but you need the url scheme syntax "hash://"
// note: since it's a URL now, the color is set to the project's tint color
attrString.addAttribute(NSLinkAttributeName, value: "hash:\(stringifiedWord)", range: matchRange)
}

}
}
self.attributedText = attrString
}

}

要使用它,我这样做:

self.myLabel.resolveHashTags()

但是,我如何检测标签何时被点击,并且他们执行 print("hashtag clicked")

有没有人对我如何做到这一点有任何想法或建议?

最佳答案

您可以实现 UITextViewDelegate 方法 textView(_:shouldInteractWithURL URL:inRange:)这允许您处理被点击的链接:

func textView(_ textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
// ...check that this is a hashtag link, and not a regular link...
print("hashtag clicked")
}

关于ios - 检测 UILabel 中的点击标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com