quin quin - 3 months ago 10
Swift Question

Customized title for alertAction ios

I'm trying to create a customized title for the

alertAction
of an
AlertController
, with conditional function depending on the state of different
switches
:

let alert = UIAlertController(title: “Got it”, message: “Please, select:”, preferredStyle: UIAlertControllerStyle.Alert)


name01: String = "name01"
name02: String = "name02"
name03: String = "name03"

if switch01.on {
let action01 = UIAlertAction(title: name01, style: .Default) { (_) in }
}
if switch02.on {
let action02 = UIAlertAction(title: name02, style: .Default) { (_) in }
}
if switch03.on {
let action03 = UIAlertAction(title: name03, style: .Default) { (_) in }
}



let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }

alert.addAction(action01)//Cannot convert value of type 'String' to expected argument type 'UIAlertAction'
alert.addAction(action02)//Cannot convert value of type 'String' to expected argument type 'UIAlertAction'
alert.addAction(action03)//Cannot convert value of type 'String' to expected argument type 'UIAlertAction'
alert.addAction(cancelAction)//No error


Thanks in advance.

Answer

You need to create the Action of AlertController out side the if block because out side the if block they are not available to access, also use if condition to just decide the title like this way.

name01: String = "name01"
name02: String = "name02"
name03: String = "name03" 

if switch01.on {
    name01 = "Title Chanhed"
}
if switch02.on {
    name02 = "Title Chanhed"
}
if switch03.on {
    name03 = "Title Chanhed"
}
let action01 = UIAlertAction(title: name01, style: .Default) { (_) in }
let action02 = UIAlertAction(title: name02, style: .Default) { (_) in }
let action03 = UIAlertAction(title: name03, style: .Default) { (_) in }
alert.addAction(action01)
alert.addAction(action02)
alert.addAction(action03)
alert.addAction(cancelAction)

Also if you want to perform action on title basis you can compare title like this way inside action handler.

let action01 = UIAlertAction(title: name01, style: .Default) { (action:UIAlertAction) in 
     if action.title == "name01" {

     }
     else {

     }
}
Comments