【Swift】获取UILabel中点击的某个功能标签文字并作出响应动作

柔情痞子 提交于 2020-07-26 21:37:54

  1、需求

  首先、针对UILabel中显示的多个功能标签,作出颜色标记提示。

  其次、对关键字作出点击响应动作。

  如图所示:  

  解决:

  1、使用正则匹配到关键字

public static var hashtag = DetectorType.custom(try! NSRegularExpression(pattern: "#[\\u4e00-\\u9fa5a-zA-Z0-9]{1,}", options: []))

  扩展:获取字符串中满足正则表达式的字符串

func matches(for regex: String, in text: String) -> [String] {
        do {
            let regex = try NSRegularExpression(pattern: regex)
            let results = regex.matches(in: text,
                                        range: NSRange(text.startIndex..., in: text))
            return results.map {
                String(text[Range($0.range, in: text)!])
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
tags = CommonUseClass._sharedManager.matches(for: "#[\\u4e00-\\u9fa5a-zA-Z0-9]{1,}", in: model.text)

  2、对关键字作出点击手势判断

extension UIGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)
        let textStorage = NSTextStorage(attributedString: label.attributedText!)

        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)

        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines
        let labelSize = label.bounds.size
        textContainer.size = labelSize

        let locationOfTouchInLabel = self.location(in: label)
        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        return NSLocationInRange(indexOfCharacter, targetRange)
    }

}

  3、获取点击的字符串,并作出响应

if self.tags.count > 0 {
                var isSelectTag = false
                var selectTag = ""
                for tag in self.tags {
                    let termsRange = (self.messageText as NSString).range(of: tag)
                    if gesture.didTapAttributedTextInLabel(label: self.messageLabel, inRange: termsRange) {
                        isSelectTag = true
                        selectTag = tag
                        break
                    }
                }
                
                if isSelectTag {
                    delegate?.selectTag(selectTag)
                    return
                }
            }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!