我正在尝试创建一个警报视图,在单击按钮时执行某个操作。我已经尝试为警报视图创建一个新类,但是当我尝试向警报视图控制器添加一个操作时,Xcode告诉我它正在期待一个声明,尽管该变量只是在错误行上方两步声明发生。这是代码
class alerts: UIAlertController {
var alertThenGenerateNewThingController: UIAlertController = UIAlertController()
var generateNewThingOkButton = UIAlertAction (title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
println ("generate new thing action")
}
alertThenGenerateNewThingController.addAction (generateNewThingOkButton) // Here is where Xcode says it expected a declaration
func alertThenGenerateNewThing (alertTitle: String, alertMessage: String) {
alertThenGenerateNewThingController = UIAlertController (title: alertTitle, message: alertMessage, preferredStyle: .Alert)
self.presentViewController (alertThenGenerateNewThingController, animated: true, completion: nil)
}
}
答案 0 :(得分:1)
一方面,你不能将UIAlertController
作为子类。其次,您只能与方法,函数或全局范围内的对象属性进行交互。在您计划显示警报的视图控制器内运行此代码:
class viewController: UIViewController {
var alertThenGenerateNewThingController: UIAlertController = UIAlertController()
var generateNewThingOkButton = UIAlertAction (title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
println ("generate new thing action")
}
override func viewDidLoad() {
alertThenGenerateNewThingController.addAction(generateNewThingOkButton)
}
func alertThenGenerateNewThing (alertTitle: String, alertMessage: String) {
alertThenGenerateNewThingController = UIAlertController (title: alertTitle, message: alertMessage, preferredStyle: .Alert)
self.presentViewController (alertThenGenerateNewThingController, animated: true, completion: nil)
}
}