Creating an Action Sheet in Swift
Code has been tested with Swift 5
Since iOS 8, UIAlertController
combined with UIAlertControllerStyle.ActionSheet
is used. UIActionSheet
is deprecated.
Here is the code to produce the Action Sheet in the above image:
class ViewController: UIViewController {
@IBOutlet weak var showActionSheetButton: UIButton!
@IBAction func showActionSheetButtonTapped(sender: UIButton) {
// Create the action sheet
let myActionSheet = UIAlertController(title: "Color", message: "What color would you like?", preferredStyle: UIAlertController.Style.actionSheet)
// blue action button
let blueAction = UIAlertAction(title: "Blue", style: UIAlertAction.Style.default) { (action) in
print("Blue action button tapped")
}
// red action button
let redAction = UIAlertAction(title: "Red", style: UIAlertAction.Style.default) { (action) in
print("Red action button tapped")
}
// yellow action button
let yellowAction = UIAlertAction(title: "Yellow", style: UIAlertAction.Style.default) { (action) in
print("Yellow action button tapped")
}
// cancel action button
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { (action) in
print("Cancel action button tapped")
}
// add action buttons to action sheet
myActionSheet.addAction(blueAction)
myActionSheet.addAction(redAction)
myActionSheet.addAction(yellowAction)
myActionSheet.addAction(cancelAction)
// present the action sheet
self.present(myActionSheet, animated: true, completion: nil)
}
}
Still need help? Watch this video tutorial. That's how I learned it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…