问题描述
使用不可编辑的UITextView,我想在iOS9 +中嵌入这样的文字:
With a non-editable UITextView, I would like to embed text like this in iOS9+:
我可以创建一个函数操纵文本,但有更简单的方法吗?
I can create a function and manipulate the text but is there a simpler way?
我看到我可以使用NSTextCheckingTypeLink,因此在Interface Builder中可以直接获取没有click here部分的文本:
I see that I can use NSTextCheckingTypeLink so getting the text clickable without the 'click here' part is straightforward in Interface Builder:
我正在使用Xcode 8和Swift 3,如果这是相关的。
I'm using Xcode 8 and Swift 3 if that's relevant.
推荐答案
使视图控制器符合 UITextViewDelegate
和以下代码。您还需要设置 isEditable = false
,或者当用户点击文本视图时文本视图将进入文本编辑模式。
Make your view controller conform to UITextViewDelegate
and a the following code. You also need to set isEditable = false
or the text view will go into text-editing mode when user taps on it.
Swift 4:
override func viewDidLoad() {
super.viewDidLoad()
// You must set the formatting of the link manually
let linkAttributes: [NSAttributedStringKey: Any] = [
.link: NSURL(string: "https://www.apple.com")!,
.foregroundColor: UIColor.blue
]
let attributedString = NSMutableAttributedString(string: "Just click here to register")
// Set the 'click here' substring to be the link
attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10))
self.textView.delegate = self
self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false
}
Swift 3及更早版本:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// You must set the formatting of the link manually
let linkAttributes = [
NSLinkAttributeName: NSURL(string: "https://www.apple.com")!,
NSForegroundColorAttributeName: UIColor.blue
] as [String : Any]
let attributedString = NSMutableAttributedString(string: "Just click here to register")
// Set the 'click here' substring to be the link
attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10))
self.textView.delegate = self
self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
这篇关于带有超链接文本的UITextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!