Ios 如何在UITextView Swift 4中使某些单词可单击以执行类似模态弹出的操作?
我正在开发一个教育应用程序,我希望用户能够点击某些关键术语,然后会出现一个带有定义的模式弹出窗口。我是Swift的新手,所以我将尝试解释我目前的方法,因为我不知道在我的解决方案中需要搜索什么 我相信我必须使用UITextView,但我不知道如何定位某些单词,并使它们像UIButton一样可点击,在那里我可以打开一个新屏幕。下面是一个我想要的例子。此外,显示什么类型的屏幕弹出窗口,您可以将其向下拖动以关闭 非常感谢你的帮助。只是在寻找正确的方向Ios 如何在UITextView Swift 4中使某些单词可单击以执行类似模态弹出的操作?,ios,swift,uitextview,Ios,Swift,Uitextview,我正在开发一个教育应用程序,我希望用户能够点击某些关键术语,然后会出现一个带有定义的模式弹出窗口。我是Swift的新手,所以我将尝试解释我目前的方法,因为我不知道在我的解决方案中需要搜索什么 我相信我必须使用UITextView,但我不知道如何定位某些单词,并使它们像UIButton一样可点击,在那里我可以打开一个新屏幕。下面是一个我想要的例子。此外,显示什么类型的屏幕弹出窗口,您可以将其向下拖动以关闭 非常感谢你的帮助。只是在寻找正确的方向 我在当前项目中已经实现了,您可以将其转换为swift
我在当前项目中已经实现了,您可以将其转换为swift
NSString* description = @"Hello world";
NSString* term_str = @"world"
NSString* detail = [NSString stringWithFormat:description,term_str];
NSMutableAttributedString *linkStr = [[NSMutableAttributedString alloc]initWithString:detail attributes:nil];
[linkStr addAttribute:NSLinkAttributeName value:NSLocalizedString(@"here_is_link_you_want_to_open", @"") range:[detail rangeOfString:term_str]];
[linkStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:[detail rangeOfString:term_str]];
_descriptionLabel.attributedText = linkStr;
_descriptionLabel.userInteractionEnabled = YES;
[_descriptionLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(your_function:)]];
实现您的功能您的_功能希望这对您有用。您可以通过以下几步来实现:
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
attributedString.addAttribute(.link, value: "https://www.hackingwithswift.com", range: NSRange(location: 19, length: 55))
textView.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
//Your code
return false
}
}
1.添加点击手势以获取特定单词2.使用UITextView委托方法:textViewDidChangeSelection
3.使用prepare Segue方法将文本字符串传递给presening ViewController。
一,
let tap=uitappesturerecognizer(目标:self,操作:#选择器(TapContextView(:))
textView.AddGestureRecognitor(点击)
轻敲手势:
@objc private final func tapOnTextView(_ tapGesture: UITapGestureRecognizer){
let point = tapGesture.location(in: textView)
if let detectedWord = getWordAtPosition(point) {
print(detectedWord)
}
}
2.使用委托方法
textView.delegate=self
func textViewDidChangeSelection(_ textView: UITextView) {
performSegue(withIdentifier: "modelSeg", sender: self)
}
谢谢你。我对Objective C也没有任何经验,但我认为这是一个领先的开始。我猜NSString是我需要熟悉的东西?然后我可以连接手势识别器打开新页面?是的,您需要创建属性字符串,有关属性字符串的更多信息,请查看apple doc,然后您需要通过添加手势使文本视图可单击
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "yourSegindentifire" {
let modelVC = segue.destination as! ModelVC
modalVC.word = word
}
}