gpt4 book ai didi

ios - 使用 Swift 的 UILabel 中的 NSAttributedString 单击事件

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:38 27 4
gpt4 key购买 nike

假设我有一个 AttributedString:“已有帐户?请登录!”。

我将这个字符串放在 UILabel 中。现在,当用户单击“登录!”时,当前的 viewController 应该转到另一个 viewController,或者在单击登录时调用某些函数。

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

最佳答案

有些答案状态不需要使用单独的手势识别器。相反,您可以将属性文本与 UITextViewDelegatetextView:shouldInteractWithURL:inRange:interaction: 结合使用实现此目的的方法,例如:

class ViewController: UIViewController, UITextViewDelegate {

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
super.viewDidLoad()

let text = NSMutableAttributedString(string: "Already have an account? ")
text.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(0, text.length))

let selectablePart = NSMutableAttributedString(string: "Sign in!")
selectablePart.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(0, selectablePart.length))
// Add an underline to indicate this portion of text is selectable (optional)
selectablePart.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range: NSMakeRange(0,selectablePart.length))
selectablePart.addAttribute(NSAttributedString.Key.underlineColor, value: UIColor.black, range: NSMakeRange(0, selectablePart.length))
// Add an NSLinkAttributeName with a value of an url or anything else
selectablePart.addAttribute(NSAttributedString.Key.link, value: "signin", range: NSMakeRange(0,selectablePart.length))

// Combine the non-selectable string with the selectable string
text.append(selectablePart)

// Center the text (optional)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
text.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, text.length))

// To set the link text color (optional)
textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 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.isEditable = false
textView.isSelectable = true
// Set the delegate in order to use textView(_:shouldInteractWithURL:inRange)
textView.delegate = self
}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

// **Perform sign in action here**

return false
}
}

关于ios - 使用 Swift 的 UILabel 中的 NSAttributedString 单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38565603/

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