我想在重试按钮中添加一个动作,但是当用户按下重试按钮时没有任何动作。
var createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.delegate = self
createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss")
createAccountErrorAlert.addButtonWithTitle("Retry")
createAccountErrorAlert.show()
确定按下按钮的索引的功能?
func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 1:
createAccount()
default:
//Some code here..
}
}
答案 0 :(得分:22)
我测试了你的代码,它对我来说工作正常,它打印出相应的结果:
func showAlert(){
var createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.delegate = self
createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss")
createAccountErrorAlert.addButtonWithTitle("Retry")
createAccountErrorAlert.show()
}
func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 1:
NSLog("Retry");
break;
case 0:
NSLog("Dismiss");
break;
default:
NSLog("Default");
break;
//Some code here..
}
}
点击“关闭”按钮时打印关闭。
答案 1 :(得分:0)
那是因为你的重试按钮的索引是1而不是0.解雇按钮的索引是0。
如果您将以下代码放在游乐场中,您将实际看到按钮的索引(如addButtonWithTitle方法中所述):
var createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss") //Prints 0
createAccountErrorAlert.addButtonWithTitle("Retry") //Prints 1
答案 2 :(得分:0)
索引错误。以下(基于iOS单视图默认应用程序模板)适用于我(我连接按钮以触发@IBAction buttonPressed
)。不要忘记让你的视图控制器成为UIAlertViewDelegate
(虽然以下工作没有这样做):
import UIKit
class ViewController: UIViewController, UIAlertViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPressed(sender : AnyObject) {
var createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.delegate = self
createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss")
createAccountErrorAlert.addButtonWithTitle("Retry")
createAccountErrorAlert.show()
}
func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
default:
println("alertView \(buttonIndex) clicked")
}
}
}
答案 3 :(得分:0)
继续我的方式,用更短的代码行:
func showAlert(){
var alert = UIAlertView(title: "Choose", message: "Which_pill", delegate: self, cancelButtonTitle:"Red")
alert.addButtonWithTitle("Blue")
alert.show()
}
func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 1: println("Blue")
case 0: println("Red")
default: println("Is this part even possible?")
}
}