2016-08-24 45 views
0

我試圖創建一個AlertControlleralertAction定製的標題,以根據不同的switches狀態條件函數:提前爲alertAction定製標題IOS

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 

感謝。

+0

'action0n'在'if swith0n.on {}'之外是無效的。他們不存在。 =>'如果swith0n.on {讓action0n = ... alert.addAction(action0n)}' – Larme

回答

0

您需要創建的AlertControllerAction出方的if塊,因爲出方的if block它們不可訪問,如果條件只是決定冠軍這樣的方式也可以使用。

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) 

此外,如果要執行標題基礎上採取行動,你可以像這樣的行動處理器中比較稱號。

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

    } 
    else { 

    } 
} 
+0

它的工作原理(我仍然不能upvote)。謝謝 – quin