如何在iPhone中创建警报框?

Bla*_*end 28 iphone objective-c uialertview ios

我想创建一个警告类型框,以便当用户尝试删除某些内容时,它会说"你确定",然后如果他们确定则为是或否.在iPhone上做这个的最好方法是什么?

And*_*rew 60

A UIAlertView是最好的方法.它将动画显示在屏幕中间,使背景变暗,并强制用户解决它,然后再返回到应用程序的正常功能.

您可以创建UIAlertView如下:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"Are you sure you want to delete this.  This action cannot be undone" delegate:self cancelButtonTitle:@"Delete" otherButtonTitles:@"Cancel", nil];
[alert show];
Run Code Online (Sandbox Code Playgroud)

这将显示消息.

然后检查他们是否点击删除或取消,使用此:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        //delete it
    }
}
Run Code Online (Sandbox Code Playgroud)

确保在你的头文件(.h)中,你可以在你的类继承的任何内容旁边添加UIAlertViewDelegateby <UIAlertViewDelegate>(即.UIViewController或者UITableViewController等等)

有关UIAlertViews查看Apple的Docs Here的所有细节的更多信息

希望有所帮助

  • 不建议使用,我们应该使用UIAlertController (2认同)

jbo*_*boi 14

这篇文章相当陈旧,但仍然是一个很好的问题.在iOS 8中,答案已经改变.今天你宁可使用'UIAlertController'和'UIAlertControllerStyle.ActionSheet'的'preferredStyle'.

像这样(swift)的代码绑定到一个按钮:

@IBAction func resetClicked(sender: AnyObject) {
    let alert = UIAlertController(
        title: "Reset GameCenter Achievements",
        message: "Highscores and the Leaderboard are not affected.\nCannot be undone",
        preferredStyle: UIAlertControllerStyle.ActionSheet)
    alert.addAction(
        UIAlertAction(
            title: "Reset Achievements",
            style: UIAlertActionStyle.Destructive,
            handler: {
                (action: UIAlertAction!) -> Void in
                gameCenter.resetAchievements()
            }
        )
    )
    alert.addAction(
        UIAlertAction(
            title: "Show GameCenter",
            style: UIAlertActionStyle.Default,
            handler: {
                (action: UIAlertAction!) -> Void in
                self.gameCenterButtonClicked()
            }
        )
    )
    alert.addAction(
        UIAlertAction(
            title: "Cancel",
            style: UIAlertActionStyle.Cancel,
            handler: nil
        )
    )
    if let popoverController = alert.popoverPresentationController {
        popoverController.sourceView = sender as UIView
        popoverController.sourceRect = sender.bounds
    }
    self.presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

会产生这个输出: 在此输入图像描述

编辑:代码在iPad,iOS 8+上崩溃.如果添加了如下所述的必要行:在另一个堆栈溢出答案