iOS Swift UIAlertView

4

我是iOS应用开发的新手,但我没有找到类似的问题。

在同一个视图控制器中是否可能有两个或更多独立的警报? 我的目标iOS版本为7.1,因此使用以下已弃用的UIAlertView方法:

let errorAlert: UIAlertView = UIAlertView()
errorAlert.delegate = self
errorAlert.message = "Are you sure?"
errorAlert.addButtonWithTitle("Yes")
errorAlert.addButtonWithTitle("No")
errorAlert.show()

这个警告会传递给一个包含一些逻辑的 switch 语句的函数。

func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) { ...

到目前为止,一切都很好。但是,当我在同一个视图控制器中创建第二个警报时,它也进入相同的函数。例如,如果我未能与数据库建立连接,我将显示不同的错误消息,但这也会进入上面的alertView函数并运行相同的switch语句。
我是否犯了明显的错误?
提前致谢。
3个回答

1
你可以尝试编写这个:

func alertView(view: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
    if view == errorAlert {
        // do your stuff..
    } else if view == anotherAlertView {
        // do your stuff for the second AlertView
    }
}

你可以将其作为答案进行检查,如果你愿意的话。 - mkz

1
你可以使用BlocksKitUIAlertView-Blocks,通过块而不是委托模式为警报按钮分配操作。这比创建大量的if alert == self.firstAlert {...} else if alert == self.secondAlert { ... } else ...条件更易读。 编辑: 好的,我认为我们需要更多解决此问题的选项!这是另一种(第四种)方法:您可以为每个UIAlertView委托创建单独的类:
class FirstErrorHandler: UIAlertViewDelegate {
    init() {
        let errorAlert: UIAlertView = UIAlertView()
        errorAlert.delegate = self
        errorAlert.message = "Are you sure?"
        errorAlert.addButtonWithTitle("Yes")
        errorAlert.addButtonWithTitle("No")
        errorAlert.show()
    }

    func alertView(view: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
          // handle first kind of errors
    }
}

class SecondErrorHandler: UIAlertViewDelegate {
    init() { ... }

    func alertView(view: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
          // handle another kind of errors
    }
}

class MyViewController {
    var alertHandler: UIAlertViewDelegate!  // store strong reference to alert handler

    ...
    func showSomeError() {
        self.alertHandler = FirstErrorHandler()
        ...
    }
}

记住,你可以将任何对象分配给UIAlertView.delegate,不仅限于UIViewController。这比在MyViewController的133行上显示警报并标记按钮,然后在MyViewController的765行的if / else语句列表中处理操作要更可读。


你说得对,其他的解决方案确实会跳来跳去代码,我已经在研究这个问题了。感谢你的帮助。 - user1162328

1

以上两个答案都是正确的并且可行的,但是为了提供另一种选择:可以设置警告视图的tag属性,所以

let errorAlert: UIAlertView = UIAlertView()
errorAlert.tag = my_tag // just some arbitrary number that you can reference later
// other stuff
errorAlert.show()

然后

func alertView(view: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
    if view.tag == my_tag {
         // view is errorAlert, perform the appropriate logic here
    }
}

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