如何在Swift中展示iOS的UIActionSheet?

120

我该如何在iOS应用程序中使用Swift展示UIActionSheet?

以下是我的代码,用于显示UIActionSheet:

@IBAction func downloadSheet(sender: AnyObject) {
    let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet) 

    let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Saved")
    })
    
    let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Deleted")
    })
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Cancelled")
    })
    optionMenu.addAction(deleteAction)
    optionMenu.addAction(saveAction)
    optionMenu.addAction(cancelAction)
    self.presentViewController(optionMenu, animated: true, completion: nil)
}

2
我认为你的方法很好,因为从ios8开始UIActionSheet已经被弃用了。所以你的风格更受欢迎。 - Saleh Masum
18个回答

2

Swift :

下面给出的示例代码可在iPhone和iPad上运行。

 guard let viewRect = sender as? UIView else {
                return
            }

        let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)
        cameraSettingsAlert.modalPresentationStyle = .Popover

        let photoResolutionAction = UIAlertAction(title: NSLocalizedString("Photo Resolution", comment: ""), style: .Default) { action in

        }
        let cameraOrientationAction = UIAlertAction(title: NSLocalizedString("Camera Orientation", comment: ""), style: .Default) { action in

        }
        let flashModeAction = UIAlertAction(title: NSLocalizedString("Flash Mode", comment: ""), style: .Default) { action in

        }
        let timeStampOnPhotoAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in

        }
        let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in

        }
        cameraSettingsAlert.addAction(cancel)
        cameraSettingsAlert.addAction(cameraOrientationAction)
        cameraSettingsAlert.addAction(flashModeAction)
        cameraSettingsAlert.addAction(timeStampOnPhotoAction)
        cameraSettingsAlert.addAction(photoResolutionAction)

        if let presenter = cameraSettingsAlert.popoverPresentationController {
            presenter.sourceView = viewRect;
            presenter.sourceRect = viewRect.bounds;
        }
        presentViewController(cameraSettingsAlert, animated: true, completion: nil)

2

传统方式:UIActionSheet

let actionSheet = UIActionSheet(title: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Destroy", otherButtonTitles: "OK")
actionSheet.actionSheetStyle = .Default
actionSheet.showInView(self.view)

// MARK: UIActionSheetDelegate

func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex  buttonIndex: Int) {
switch buttonIndex {
    ...
   }
}

新的方式:UIAlertController
let alertController = UIAlertController(title: nil, message: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", preferredStyle: .ActionSheet)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
  // ...
 }
 alertController.addAction(cancelAction)

let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
   // ...
}
alertController.addAction(OKAction)

let destroyAction = UIAlertAction(title: "Destroy", style: .Destructive) { (action) in
println(action)
}
alertController.addAction(destroyAction)

self.presentViewController(alertController, animated: true) {
// ...
}

2

Swift 3 在iPad上从UIBarButtonItem中显示UIAlertController

要在iPad上从UIBarButtonItem中显示UIAlertController,您需要在其中一个视图控制器的viewDidLoad方法中添加以下代码:
```swift if let popoverController = alertController.popoverPresentationController { popoverController.barButtonItem = yourBarButtonItem } ```
这将使UIAlertController以弹出窗口的形式显示,并将其锚定到指定的UIBarButtonItem。请确保将"yourBarButtonItem"替换为您自己的UIBarButtonItem实例。
        let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)

    alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
        print("User click Approve button")
    }))

    alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
        print("User click Edit button")
    }))

    alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
        print("User click Delete button")
    }))

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler:{ (UIAlertAction)in
        print("User click Dismiss button")
    }))

    if let presenter = alert.popoverPresentationController {
        presenter.barButtonItem = sender
    }

    self.present(alert, animated: true, completion: {
        print("completion block")
    })

1

在Swift4中为ActionSheet添加警告的代码

   *That means when we click actionsheet values(like edit/ delete..so on) it shows 
   an alert option that is set with Yes or No option*


   class ViewController: UIViewController
   {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func action_sheet1(_ sender: Any) {




    let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)

    action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Approve button")



        let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))




    action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Edit button")

        let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))




    action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
        print("User click Delete button")



        let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))





    action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
         print("User click cancel button")


        let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))



        self.present(action_sheet1, animated: true, completion: {
        print("completion block")
    })
}


}

0

Swift 5+ 只需调用此函数,非常简单和流畅,Boommmmmm!!!

let IPAD = UIDevice.current.userInterfaceIdiom == .pad


//Mark:- Choose Image Method
func funcMyActionSheet() {
    var myActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
    myActionSheet.view.tintColor = UIColor.black
    let galleryAction = UIAlertAction(title: "Gallery".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        self.openGallary()
    })
    let cmaeraAction = UIAlertAction(title: "Camera".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        self.openCamera()
    })
    let cancelAction = UIAlertAction(title: "Cancel".localizableString(language: Defaults.selectedLanguageCode), style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
    })
    

    if IPAD {
        //In iPad Change Rect to position Popover
        myActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.alert)
    }
    myActionSheet.addAction(galleryAction)
    myActionSheet.addAction(cmaeraAction)
    myActionSheet.addAction(cancelAction)
    print("Action Sheet call")
    
    self.present(myActionSheet, animated: true, completion: nil)
}

0

用于填充动态操作列表,并监听所选操作:

var categories = ["Science", "History", "Industry", "Agriculture"]

var handlerSelectedCategory: ((Int) -> ())?

func prepareActions(for title: String, index: Int) -> UIAlertAction {

    let alertAction = UIAlertAction(title: title, style: .default) { (action) in
        self.handlerSelectedCategory?(index)
    }

    return alertAction
}

@objc func presentActions() {

    let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    // add dymamic options
    for (index, element) in self.categories.enumerated() {
         optionMenu.addAction(prepareActions(for: element, index: index))
    }
    // cancel
    let cancelAction = UIAlertAction(title: "Cancel", style: .destructive)
    optionMenu.addAction(cancelAction)

    handlerSelectedCategory = { index in
        print(index, self.categories[index])
    }

    self.present(optionMenu, animated: true, completion: nil)
}

0

您可以使用以下代码在Swift 4中实现警告和操作表:

@IBAction func alert_act(_ sender: Any) {
    do {    
        let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)
        
        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
        
        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
        
        self.present(alert, animated: true, completion: nil)
    }
}

@IBAction func action_sheet1(_ sender: Any) {      
    let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)
    
    let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
    let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    
    action_sheet1.addAction(defaultAction)
    action_sheet1.addAction(deleteAction)
    action_sheet1.addAction(cancelAction)
    
    self.present(action_sheet1, animated: true, completion: nil)
}

-1
您可以使用以下代码在Swift中打开ActionSheet:
let alert = UIAlertController(title: enter your title, message: "Enter your messgage. ", preferredStyle: UIAlertControllerStyle.Alert)

alert.addTextFieldWithConfigurationHandler(configurationTextField)

alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:{ (UIAlertAction)in
    print("User click Cancel button")
}))

alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
    print("User click Ok button")
}))

self.presentViewController(alert, animated: true, completion: {
    print("completion block")
})

配置文本字段应该是什么? - AMAN77
在这里你会找到: func configurationTextField(textField: UITextField!) { print("配置文本框")if textField != nil { self.textField = textField! self.textField.delegate = self //保存对UITextField的引用 self.textField.text = "" self.textField.keyboardType = UIKeyboardType.NumberPad self.textField.placeholder = "输入延迟时间(秒)" }} - Anny

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