gpt4 book ai didi

ios - 如何仅为 Swift 3 中的 UILabel 的特定范围设置点击手势

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:54 24 4
gpt4 key购买 nike

我有一个 attributed string 设置为 UILabelmultiple underlinescolors 如下图

enter image description here

我知道如何为整个标签设置点击手势(启用用户交互)和下面是我的代码我所做的包括设置下划线并为多个范围设置字体颜色

import UIKit

class ViewController: UIViewController {


@IBOutlet weak var mylabel: UILabel!

var theString = "I have agree with the terms and conditions and privacy policy"

override func viewDidLoad() {
super.viewDidLoad()

mylabel.text = theString


let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.printme))
mylabel.addGestureRecognizer(tap)

setUnderline(theText: theString)

// Do any additional setup after loading the view, typically from a nib.
}

func printme() {
print("print this")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func setUnderline(theText : String) {
//set up underline
let textRange1 = NSMakeRange(22, 19)
let textRange2 = NSMakeRange(47, (theText.characters.count-47))
let attributedText = NSMutableAttributedString(string : theText)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: textRange1)
attributedText.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: textRange2)


//setup colors
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 22,length: 20))
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 47,length: (theText.characters.count-47)))

mylabel.attributedText = attributedText

}
  • tap 手势适用于整个标签。我想要的是当用户点击“条款和条件”时触发不同的功能,当用户点击“隐私政策”时触发另一个不同的功能。我怎样才能做到这一点。

Note : I want to fire two different functions one for "terms and conditions" tap, and other for "privacy policy" tap, and do not want to just open links

最佳答案

    import UIKit

protocol SSGastureDelegate:NSObjectProtocol {
func callBack()
}
class SSUnderLineLabel: UILabel {
var tapGesture: UITapGestureRecognizer?

//Make weak refernece for SSGastureDelegate
weak var delegate:SSGastureDelegate?

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.initialization()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialization()
}

func initialization(){
let newsString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
let textRange = NSString(string: self.text!)
let substringRange = textRange.range(of: "Terms and Conditions") // You can add here for own specific under line substring
newsString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: substringRange)
// self.attributedText = newsString.copy() as? NSAttributedString
self.attributedText = newsString
self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapResponse))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tapGesture!)

}

func tapResponse(recognizer: UITapGestureRecognizer) {

let text = (self.text)!
let termsRange = (text as NSString).range(of: "Terms and Conditions")
if (tapGesture?.didTapAttributedTextInLabel(label: self, inRange: termsRange))! {
print("Tapped terms conditions")
self.delegate?.callBack()
}
else {
print("Tapped none ")
}
}

}

//MARK:UITapGestureRecognizer Extension
//MARK:
extension UITapGestureRecognizer {

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

// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)

// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = label.lineBreakMode
textContainer.maximumNumberOfLines = label.numberOfLines
let labelSize = label.bounds.size
textContainer.size = labelSize
// Find the tapped character location and compare it to the specified range
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)
}

}*`enter code here`




**How to use it:**
Assign this class for your label and follow these steps:
Demo for use class:

ViewController.swift
//===============

class ViewController: UIViewController,SSGastureDelegate {
@IBOutlet var underlineLbl: SSUnderLineLabel!

override func viewDidLoad() {
super.viewDidLoad()
self.underlineLbl.delegate = self
}
//Implement Delegate Method
func callBack()
{
//Open a specific vc for underline tap are`enter code here`a.
let termsconditionsVC = storyboard?.instantiateViewController(withIdentifier: "TermsConditionsVC") as! TermsConditionsVC
self.present(termsconditions, animated: true, completion: nil)

}
}*

关于ios - 如何仅为 Swift 3 中的 UILabel 的特定范围设置点击手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40512606/

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