我想在我的UIAlert中添加一个单独的取消按钮。
我知道怎么用UIActionSheet来做,但UIAlert也应该可以,对吗?
var sheet: UIActionSheet = UIActionSheet();
let title: String = "...";
sheet.title = title;
sheet.delegate = self;
sheet.addButtonWithTitle("Cancel");
sheet.addButtonWithTitle("...")
sheet.cancelButtonIndex = 0;
sheet.showInView(self.view);
这将有一个......按钮和一个分开的取消按钮。
所以有人知道怎么做
var alert = UIAlertController(title: "...", message: "....", preferredStyle: UIAlertControllerStyle.ActionSheet)
我是xcode和swift的新手,很抱歉,如果这个问题很愚蠢或任何事情......
答案 0 :(得分:39)
它非常简单,但与以前的工作方式有所不同。现在,您可以为警报添加“操作”。然后,这些操作由设备上的按钮表示。
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
以上是简单取消按钮所需的代码 - 请记住,警报的解除是自动完成的,所以不要把它放在你的处理程序中。如果您想创建另一个执行某些操作的按钮,请使用以下代码:
alert.addAction(UIAlertAction(title: "Button", style: UIAlertActionStyle.Default, handler: { action in
println("This button now calls anything inside here!")
}))
希望我理解你的问题,这就回答了你的要求。我还要补充一点,在添加了所有“操作”后,您将使用以下代码显示警报:
self.presentViewController(alert, animated: true, completion: nil)
希望这有帮助!
答案 1 :(得分:6)
我想继续为特定问题提供具体答案。用户询问了"取消"的实施情况。按钮,而不是默认按钮。看看下面的答案!
let alertController = UIAlertController(title: "Select one", message: "Hey! Press a button", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
答案 2 :(得分:1)
这可能是您看到的最糟糕的编码答案,但我能够通过尝试来满足您的要求:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UILabel *alertLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, alertController.view.frame.size.width, 2)];
alertLine.backgroundColor=[UIColor blackColor];
[alertController.view.preferredFocusedView addSubview:alertLine];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self.navigationController presentViewController:alertController animated:YES completion:nil];