如何创建 UIActionSheet 动作? [英] How to create UIActionSheet actions?
问题描述
我知道我必须设置委托(我这样做是这样的:class ShiftOverview: UITableViewController, UIActionSheetDelegate {...
)但是当我点击按钮时仍然没有响应.
I know I have to set the delegate (I did so like this: class ShiftOverview: UITableViewController, UIActionSheetDelegate {...
) but I'm still getting no response when I tap the buttons.
看起来您也不能使用 UIAlertController
在函数内设置委托...
It doesn't look like you can set the delegate within the function with UIAlertController
either...
@IBAction func takeShift(sender: AnyObject) {
let myActionSheet = UIAlertController (title: "Confirm", message: "Test message", preferredStyle: UIAlertControllerStyle.ActionSheet)
let actionOne = UIAlertAction (title: "Take Shift", style: .Default, handler: nil)
let actionTwo = UIAlertAction (title: "View ESA", style: .Default, handler: nil)
let actionCancel = UIAlertAction (title: "Cancel", style: .Cancel, handler: nil)
myActionSheet.addAction(actionOne)
myActionSheet.addAction(actionTwo)
myActionSheet.addAction(actionCancel)
self.presentViewController(myActionSheet, animated: true, completion: nil)
}
func actionSheet (myActionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
switch buttonIndex {
case 0:
println ("test0")
break
case 1:
println ("test1")
break
case 2:
println ("test2")
break
default:
println("nope")
}
}
推荐答案
在 iOS 8 之前,UIAlertViews 和 UIActionSheets 是单独的控件.然而,在 iOS 8 中,一个新类 UIAlertController 将这两个控件合并到一个易于使用的类中.
Prior to iOS 8, UIAlertViews and UIActionSheets were separate controls. In iOS 8 however, a new class, UIAlertController, combines both these controls into a single, easy to use class.
与过去使用这些控件的委托模式不同,您现在传递一个要调用的闭包.handler
等于 nil
的地方就是你放置代码的地方.
Rather than using the delegation pattern like these controls used to, you now pass a closure to be called. The places where you have handler
equal to nil
is where you put your code.
这可能是添加的,因为 Swift 将闭包视为一等公民,而 Objective C 没有那么多(使用块).
This is likely added because Swift treats closures as first-class citizens, while Objective C did not as much (with blocks).
应该是:
@IBAction func takeShift(sender: AnyObject) {
let myActionSheet = UIAlertController (title: "Confirm", message: "Test message", preferredStyle: UIAlertControllerStyle.ActionSheet)
let actionOne = UIAlertAction (title: "Take Shift", style: .Default, handler: { (action) in
println("test0")
})
let actionTwo = UIAlertAction (title: "View ESA", style: .Default, handler: { (action) in
println("test1")
})
let actionCancel = UIAlertAction (title: "Cancel", style: .Cancel, handler: { (action) in
println("test2")
})
myActionSheet.addAction(actionOne)
myActionSheet.addAction(actionTwo)
myActionSheet.addAction(actionCancel)
self.presentViewController(myActionSheet, animated: true, completion: nil)
}
在 NSHipster 关于 UIAlertControllers 的文章 或其 文档.
这篇关于如何创建 UIActionSheet 动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!