我在TextView中有文本,文本中有一些单词,如果用户单击它,则应该显示带有单词的警报,例如,这可能意味着单词已翻译成某种语言。
我尝试使用字典,其中的键是文本中的单词,警报中的单词是一个值。但这行不通。出现错误单词的警报。
import UIKit
class ViewController: UIViewController , UITextViewDelegate {
private let kURLString = "https://www.mywebsite.com"
let dictionary = ["website" : "Johny" , "visit" : "Bilbo"]
var keyOne : String?
var valueOne : String?
@IBOutlet weak var text: UITextView! {
didSet{
text.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
let originalText = "Please visit the website for more information."
let attributedOriginalText = NSMutableAttributedString(string: originalText)
for (key , value) in dictionary {
keyOne = key
valueOne = value
let linkRange = attributedOriginalText.mutableString.range(of: keyOne!)
attributedOriginalText.addAttribute(.link, value: kURLString, range: linkRange)
}
text.attributedText = attributedOriginalText
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (URL.absoluteString == kURLString) {
alert(value: valueOne!)
}
return false
}
func alert (value : String) {
let alert = UIAlertController (title: nil, message: value, preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Ок", style: .default , handler : { (UIAlertAction) in
self.viewDidLoad()
})
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
}
答案 0 :(得分:1)
您可以通过创建扩展以便下次重用来实现,如以下代码所示:
extension UITextView{
func textRangeFromNSRange(range:NSRange)->String{
let myNSString = self.text as NSString
return myNSString.substring(with: range)
}
}
用法:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (URL.absoluteString == kURLString) {
alert(value: textView.textRangeFromNSRange(range: characterRange))
}
return false
}
如果您想从字典中获得价值,可以执行以下操作:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (URL.absoluteString == kURLString) {
alert(value: dictionary[textView.textRangeFromNSRange(range: characterRange)]!)
}
return false
}
注意:请确保textView中的链接是可选的,但不可编辑。
答案 1 :(得分:0)
仅当文本视图是可选的但不可编辑时,文本视图中的链接才是交互式的。
设置可编辑的false和可选的true:
text.isEditable = false
text.isSelectable = true
要从textview中获取所选文本,这是您的案例中的关键,请使用以下功能:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if let key = textView.text.substring(with: characterRange){
if let value = dictionary[String(key)]{
print("text :",value)
alert(value: value)
}
}
return false
}
使用扩展名来获取具有范围的子字符串:
extension String {
func substring(with nsrange: NSRange) -> Substring? {
guard let range = Range(nsrange, in: self) else { return nil }
return self[range]
}
}