我的应用程序中有一个注册页面,我希望用户能够在按下UILabel内的文本时查看服务条款(TermsOfServiceViewController)和隐私政策(PrivacyPolicyViewController)。
我的声明如下:“选中此框即表示您同意我们的服务条款和隐私策略”。当用户按“服务条款”时,我希望他们看到TermsOfServiceViewController;当用户按“隐私策略”时,我希望他们看到PrivacyPolicyViewController。
现在我的代码是这样的:
override func viewDidLoad() {
super.viewDidLoad()
let termsOfServiceViewController = NavigationTapGestureRecognizer(target: self, action: #selector(termsOfServiceVCTapped))
termsOfServiceViewController.viewController = self
let privacyPolicyViewController = NavigationTapGestureRecognizer(target: self, action: #selector(privacyPolicyVCTapped))
privacyPolicyViewController.viewController = self
let string = NSMutableAttributedString(string: "By checking this box, you agree to our ")
let attributedTermsOfService = NSMutableAttributedString(string: "Terms of Service", attributes: [NSAttributedString.Key.link: termsOfServiceViewController, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue, NSAttributedString.Key.underlineColor: UIColor.appColor(LPColor.LightestPurple)!, NSAttributedString.Key.foregroundColor: UIColor.appColor(LPColor.LightestPurple)!])
let additionalString = NSMutableAttributedString(string: " and our ")
let attributedPrivacyPolicy = NSMutableAttributedString(string: "Privacy Policy", attributes: [NSAttributedString.Key.link: privacyPolicyViewController, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue, NSAttributedString.Key.underlineColor: UIColor.appColor(LPColor.LightestPurple)!, NSAttributedString.Key.foregroundColor: UIColor.appColor(LPColor.LightestPurple)!])
string.append(attributedTermsOfService)
string.append(additionalString)
string.append(attributedPrivacyPolicy)
agreementLabel.attributedText = string
agreementLabel.addGestureRecognizer(termsOfServiceViewController)
agreementLabel.addGestureRecognizer(privacyPolicyViewController)
agreementLabel.isUserInteractionEnabled = true
}
@objc func termsOfServiceVCTapped() {
let vc = TermsOfServiceViewController.storyboardInstance(storyboardName: "Login") as! TermsOfServiceViewController
navigationController?.pushViewController(vc, animated: true)
}
@objc func privacyPolicyVCTapped() {
let vc = PrivacyPolicyViewController.storyboardInstance(storyboardName: "Login") as! PrivacyPolicyViewController
navigationController?.pushViewController(vc, animated: true)
}
现在,这段代码允许点击整个UILabel(我相信这是因为我将addGestureRecognizer添加到整个agreementLabel),并且它只会进入privacyPolicyViewController。有什么方法可以将它们彼此分开,并且只在用户点击实际文本而不是整个标签时才检测点击?
另外,我的NavigationTapGestureRecognizer看起来像这样:
class NavigationTapGestureRecognizer: UITapGestureRecognizer {
var viewController: UIViewController?
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event!)
}
}
如果有任何建议,我可以得到,这将是太棒了。提前感谢。
2条答案
按热度按时间trnvg8h31#
bksxznpy2#
所以经过一番研究,我想出了解决办法。请看下面:
创建UITapGestureRecognizer的扩展:
然后将属性添加到字符串和UITapGestureRecognizer:
引用此链接:Tap on a part of text of UILabel