IOS Swift UIAlertView

I am new to iOS app development, but I have not been able to find a similar question.

Is it possible to have two or more unique alerts in one controller? I focus on iOS 7.1 and therefore use the following deprecated UIAlertView method:

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

This warning goes to a function that contains some logic in the switch statement.

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

So far so good, but when I create a second warning inside the same view controller, it also goes into the same function. For example, if I cannot establish a connection to the database, I will show another error message, but this also applies to the above alertView function and is executed through the same switch statement.

Is there an obvious mistake I'm making?

Thanks in advance.

+4
3

:

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

BlocksKit UIAlertView-Blocks . , if alert == self.firstAlert {...} else if alert == self.secondAlert { ... } else ....

EDIT: , , moar ! (4-) : 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. , 133 MyViewController, if/else 765 MyViewController.

+1

The two answers above are correct and will work, but only in order to provide another alternative: it is possible to set the property tagfor alert views, therefore

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

and then

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

Source: https://habr.com/ru/post/1608080/


All Articles