2015-01-07 81 views
18

我有一個兼容iPhone和iPad佈局的應用程序。對於iPhone佈局,我爲iPad創建了Action Sheet和Pop。問題是彈出的箭頭不指向我點擊的按鈕。下面是我的代碼....彈出窗口不會指向按鈕

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) 

回答

69

設置sourceViewsourceRectbuttonbutton.bounds
您可以根據視圖的佈局選擇allowedArrowDirections。

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

如果該按鈕是一個BarButtonItem使用此代碼。

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

好吧,沒有工作無論是。該按鈕實際上是一個'UIBarButtonItem'。我改變了函數作爲'@IBAction func userOptions(button:UIBarButtonItem)',並且它拋出一個錯誤:'[UIBarButtonItem bounds]:無法識別的選擇器發送' –

+0

檢查我的修改答案@SrujanSimha – rakeshbs

+0

完美!謝謝你:) –

2

對於我使用發件人和鑄造作爲UIView。

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

alertController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up 
0

SWIFT 3

這爲我工作時,我的按鈕是一個的UIBarButtonItem:

if UIDevice.current.userInterfaceIdiom == .pad { 

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

} 

整個代碼如下片段:

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) 
}