点击我的点击位置(Swift)
我怎样才能这样做,当我点击链接时,弹出窗口会出现在图片中所示的点击旁边?
我尝试添加它但是它显示在左上角
optionMenu.popoverPresentationController?.sourceView = self.view
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if (URL.scheme?.contains("mailto"))! {
let optionMenu = UIAlertController(title: nil, message: "\(URL)", preferredStyle: .actionSheet)
// 2
let NewAction = UIAlertAction(title: "New Mail Message", style: .default, handler: { (alert: UIAlertAction!) -> Void in
print("New Mail Message")
UIApplication.shared.open(URL)
})
//
let CopyAction = UIAlertAction(title: "Copy", style: .default, handler: { (alert: UIAlertAction!) -> Void in
print("Copy Email")
UIPasteboard.general.string = "\(URL)"
})
//
let CancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (alert: UIAlertAction!) -> Void in
print("Cancelled")
})
// 4
optionMenu.addAction(NewAction)
optionMenu.addAction(CopyAction)
optionMenu.addAction(CancelAction)
// 5
self.present(optionMenu, animated: true) {
print("Email menu presented")
}
} else {
//
}
}
答案 0 :(得分:2)
你几乎完成了工作。您需要的是检测链接在屏幕上的位置并在那里显示警报。
presentationController的预设置:
//You may also consider allowing UIPopoverArrowDirection.up.down if it suits your case.
optionMenu.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
optionMenu.popoverPresentationController?.sourceView = textView
如何找到链接的位置:
guard let beginning = textView.position(from: textView.beginningOfDocument, offset: characterRange.location),
let end = textView.position(from: textView.beginningOfDocument, offset: characterRange.location + characterRange.length),
let textRange = textView.textRange(from: beginning, to: end) else {
//Cannot locate link
return false
}
//move the presentationController to point to the link
optionMenu.popoverPresentationController?.sourceRect = textView.firstRect(for: textRange)
如果您对什么样的魔法感兴趣,可以阅读更多here