使用swift在UILabel中单击NSAttributedString事件

假设我有一个AttributedString:“已经有一个帐户?登录!”。 我将此字符串放在UILabel中。 现在,当用户点击“登录!”时,当前的viewController应该转到另一个viewController,或者在点击登录时调用某个函数。

任何代码或建议都应该没问题。

一些答案表明,没有必要使用单独的手势识别器。 相反,您可以将属性文本与UITextViewDelegatetextView(_:shouldInteractWithURL:inRange)方法结合使用来实现此目的,例如:

 class ViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let text = NSMutableAttributedString(string: "Already have an account? ") text.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: NSMakeRange(0, text.length)) let selectablePart = NSMutableAttributedString(string: "Sign in!") selectablePart.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: NSMakeRange(0, selectablePart.length)) // Add an underline to indicate this portion of text is selectable (optional) selectablePart.addAttribute(NSUnderlineStyleAttributeName, value: 1, range: NSMakeRange(0,selectablePart.length)) selectablePart.addAttribute(NSUnderlineColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, selectablePart.length)) // Add an NSLinkAttributeName with a value of an url or anything else selectablePart.addAttribute(NSLinkAttributeName, value: "signin", range: NSMakeRange(0,selectablePart.length)) // Combine the non-selectable string with the selectable string text.appendAttributedString(selectablePart) // Center the text (optional) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.Center text.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, text.length)) // To set the link text color (optional) textView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)] // Set the text view to contain the attributed text textView.attributedText = text // Disable editing, but enable selectable so that the link can be selected textView.editable = false textView.selectable = true // Set the delegate in order to use textView(_:shouldInteractWithURL:inRange) textView.delegate = self } func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { // **Perform sign in action here** return false } } 

您可以使用textview打开View Controller或使子串可点击,而不是Label

  1. 为要使其可点击的字符串创建属性

     let linkAttributes = [ NSLinkAttributeName: NSURL(string: "https://www.apple.com")!, NSForegroundColorAttributeName: UIColor.blue ] as [String : Any] 
  2. 使你的字符串归因于字符串

     let attributedString = NSMutableAttributedString(string:"My name is Jarvis") attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10)) 

    你可以在这里给你的自定义范围。

  3. 将归因文本添加到textview

     YourTextView.attributedText = attributedString 
  4. 然后实现textview的以下委托方法,实现Url的交互

     func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { // here write your code of navigation return false } 
  5. 如果你想用标签来做,点击这里( 如何在NSAttributedString中创建一个可点击的链接 )

您可以在标签/视图中添加点按手势识别器,或者可以将带有自定义URL协议的链接嵌入到属性字符串中,使用UITextView并打开链接检测。 然后,您需要实现UITextView委托方法来响应链接。

编辑:

我在Github上有一个名为DatesInSwift (link)的演示项目,它在UITextView中实现了可点击链接。 在ViewController.swift查看UITextView委托方法textView(_:shouldInteractWithURL:inRange) 。 这是告诉文本视图它应该响应URL的方法。

然后,您必须实现UIApplicationDelegate方法来处理URL。 示例应用程序使用application(_:openURL:sourceApplication:annotation) ,这在iOS 9中已弃用。对于新开发,您应该使用application(_:openURL:options:)来代替。

您还需要在info.plist中添加CFBundleURLTypes / CFBundleURLSchemes条目以注册自定义URL方案(如myompany.myapp.loginURL ),以便单击嵌入的URL来调用您的应用程序。

基于@Lindsey Scott的语言更新回答:)

斯威夫特4

 class ViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let text = NSMutableAttributedString(string: "Already have an account? ") text.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 12), range: NSRange(location: 0, length: text.length)) let interactableText = NSMutableAttributedString(string: "Sign in!") interactableText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 12), range: NSRange(location: 0, length: interactableText.length)) // Adding the link interaction to the interactable text interactableText.addAttribute(NSAttributedStringKey.link, value: "SignInPseudoLink", range: NSRange(location: 0, length: interactableText.length)) // Adding it all together text.append(interactableText) // Set the text view to contain the attributed text textView.attributedText = text // Disable editing, but enable selectable so that the link can be selected textView.isEditable = false textView.isSelectable = true textView.delegate = self } func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { //Code to the respective action return false } } 

您需要使用UITextView

 class ViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let attribute:NSAttributedString = NSAttributedString(string: "Already have an account? Sign in!", attributes: ["Tag" : true]) textView.attributedText = attribute let tap = UITapGestureRecognizer(target: self, action: #selector(self.textTapped(_:))) tap.delegate = self textView.userInteractionEnabled = true textView.addGestureRecognizer(tap) } func textTapped(recognizer:UITapGestureRecognizer) { let textView:UITextView = recognizer.view as! UITextView // Location of the tap in text-container coordinates let layoutManager = textView.layoutManager var location:CGPoint = recognizer.locationInView(textView) location.x -= textView.textContainerInset.left location.y -= textView.textContainerInset.top var distance:CGFloat? // Find the character that's been tapped on let characterIndex = layoutManager.characterIndexForPoint(location, inTextContainer: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: &distance!) if characterIndex < textView.textStorage.length{ var range:NSRange? let value = textView.attributedText.attribute("Tag", atIndex: characterIndex, effectiveRange: &range!) if value { // add your code here } } } } 

您可以将tapGesture应用于标签。

创建点按手势识别器:

 let tapGesture = UITapGestureRecognizer(target: self, action: "YOUR_METHOD:") 

添加手势识别器到标签:

 YOUR_LABEL.addGestureRecognizer(tapGesture) 

使用此方法执行任务:

 func YOUR_METHOD(sender:UITapGestureRecognizer){ // Perform your operations here. }