弹出框没有指向按钮

29

我有一个应用程序,适用于iPhone和iPad的布局。对于iPhone布局,我创建了操作表和Pop Over,而对于iPad,则是 Pop Over。问题在于 Pop Over 的箭头没有指向我点击的按钮。以下是我的代码....

let actionSheet = UIAlertController(title: "Choose an option",
            message: "Message",
            preferredStyle: .ActionSheet)
...

if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
{
     // for iPad
     actionSheet.popoverPresentationController?.sourceView = self.view
     actionSheet.popoverPresentationController?.sourceRect = self.view.bounds;
     actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.allZeros;
}

self.presentViewController(actionSheet, animated: true, completion: nil)
3个回答

107

sourceViewsourceRect设置为buttonbutton.bounds
根据您的视图布局可以选择允许的permittedArrowDirections

actionSheet.popoverPresentationController?.sourceView = button
actionSheet.popoverPresentationController?.sourceRect = button.bounds;
actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Left;

如果按钮是一个BarButtonItem,请使用此代码。

actionSheet.popoverPresentationController?.barButtonItem = button
actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up;

好的,那也不行。按钮实际上是一个UIBarButtonItem。我已经将函数更改为@IBAction func userOptions(button: UIBarButtonItem),但它抛出了一个错误:[UIBarButtonItem bounds]: unrecognized selector sent - Srujan Simha
请检查我修改后的答案 @SrujanSimha - rakeshbs
sourceView和sourceRect有什么区别? - Paweł Brewczynski
1
使用 bounds 而不是 frame 是我正在寻找的。谢谢! - Beltalowda

3

对我来说,使用发送者并将其转换为UIView是有效的。

alertController.popoverPresentationController?.sourceView = sender as! UIView
alertController.popoverPresentationController?.sourceRect = sender.bounds

alertController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up

1

SWIFT 3

当我的按钮是UIBarButtonItem时,这段代码对我起作用:

if UIDevice.current.userInterfaceIdiom == .pad {

    if controller.responds(to: "popoverPresentationController") {
        controller.popoverPresentationController?.barButtonItem = YourUIBarButtonName
    }

}

Entire code snippet below:

func presentActivitySheet() {

    let controller = UIActivityViewController(activityItems: [document.fileURL], applicationActivities: nil)

        if UIDevice.current.userInterfaceIdiom == .pad {

            if controller.responds(to: "popoverPresentationController") {
            controller.popoverPresentationController?.barButtonItem = YourUIBarButtonName
            }

        }

    present(controller, animated: true, completion: nil)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接