如何在单个标签中点击多个单词

How to get multiple word click in a single label

我是 swift 的新手,我想获得多个可点击的词和每个词的不同点击手势

EX:- "Please read terms & condition and Privacy Policy Properly" 我需要点击 "terms & condition" 和 print("terms") 当点击 "Privacy Policy " 它应该打印 ("Privacy ")

我尝试了一些东西,但没有像预期的那样正确输出

let txt = NSMutableAttributedString(string: labelCreateAccount.text!)
        let range = (labelCreateAccount.text! as NSString).range(of: "Term & Condition")
        let range1 = (labelCreateAccount.text! as NSString).range(of: "Privacy Policy")
        
        txt.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red] , range: range)
        txt.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red] , range: range1)
        labelCreateAccount.addGestureRecognizer(UITapGestureRecognizer(target:range, action: #selector(LabelTapAccount)))

        labelCreateAccount.addGestureRecognizer(UITapGestureRecognizer(target:range 1, action: #selector(LabelTapAccount)))

        labelCreateAccount.attributedText = txt
        labelCreateAccount.isUserInteractionEnabled = true

创建扩展 UITapGestureRecognizer

extension UITapGestureRecognizer {

    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: 0 );
        
        let lineModifier = Int(ceil(locationOfTouchInLabel.y / label.font.lineHeight)) - 1
        let rightMostFirstLinePoint = CGPoint(x: labelSize.width, y: 0)
        let charsPerLine = layoutManager.characterIndex(for: rightMostFirstLinePoint, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        let adjustedRange = indexOfCharacter + (lineModifier * charsPerLine)
        
        return NSLocationInRange(adjustedRange, targetRange)
    }
    
}

extension Range where Bound == String.Index {
    var nsRange: NSRange {
        return NSRange(location: self.lowerBound.encodedOffset,
                       length: self.upperBound.encodedOffset -
                        self.lowerBound.encodedOffset)
    }
}

将 TapGesture 添加到目标标签和侦听器上,检查来自 attributedText 的目标字符串上的点击:

@objc private func settingTapped(_ sender: UITapGestureRecognizer) {
    guard let range = self.yourLabel.text?.range(of: "your Text")?.nsRange else {
        return
    }
    
    if sender.didTapAttributedTextInLabel(label: self.yourLabel, inRange: range) {
        // your work
    }
    
}

现在设置点击标签:

let txt = NSMutableAttributedString(string: labelCreateAccount.text!)
            let range = (labelCreateAccount.text! as NSString).range(of: "Term & Condition")
            let range1 = (labelCreateAccount.text! as NSString).range(of: "Privacy Policy")
            
            txt.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red] , range: range)
            txt.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red] , range: range1)

            labelCreateAccount.attributedText = txt
            
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.settingTapped(_:)))
            self.labelCreateAccount.addGestureRecognizer(tap)
            self.labelCreateAccount.isUserInteractionEnabled = true