单击选项时弹出窗口位置不正确

Popover location is not coming proper on click of an options

我点击的弹出窗口位置 (Swift)

我怎样才能做到当我点击 link 时弹出窗口会出现在点击旁边,如图所示?


我想添加但是左上角显示了

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 {
    //
    }
}

您几乎完成了任务。您需要做的是检测 link 在屏幕上的位置并在那里显示警报。

presentationController 的预设置:

//You may also consider allowing UIPopoverArrowDirection.up.down if it suits your case.
optionMenu.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
optionMenu.popoverPresentationController?.sourceView = textView

如何找到 link 所在的位置:

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