我想在没有segues的帮助下将Bool值从视图控制器传递给另一个。所以我提到了&有代表。
我在我的应用程序中应用了代理。但是没有调用Delegate方法。我不知道我在哪里弄错了。
所以请帮助我。
MainViewController
class MainViewController: UIViewController, WriteValueBackDelegate {
@IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
第二视图控制器
class LoginController: UIViewController {
@IBOutlet weak var LoginLabel: UILabel!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var pwd: UITextField!
var LoggedInL :Bool?
var mydelegate: WriteValueBackDelegate?
override func viewDidLoad() {
super.viewDidLoad() }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSubmit(sender: AnyObject) {
Alamofire.request(.GET, "http://www.jive.com/index.php/capp/user_verification/\(email.text)/\(pwd.text)")
.responseJSON { (_, _, data, _) in
println(data)
let json = JSON(data!)
let name = json["first_name"].stringValue
let status = json["valid_status"].intValue
println(status)
var e = self.email.text
println(e)
self.LoginLabel.text = "Hey \(name)!"
if status == 1{
println("Correect")
self.LoggedInL = true
self.mydelegate?.writeValueBack(true)
}else {
self.LoggedInL = false
println("Error")
}
}
navigationController!.popViewControllerAnimated(true)
}
}
protocol WriteValueBackDelegate {
func writeValueBack(value: Bool)
}
答案 0 :(得分:3)
你没有初始化委托,也没有必要,委托通常用于异步回调。这样做:
class MainViewController: UIViewController {
static var sharedInstace : MainViewController?;
@IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
MainViewController.sharedInstace = self; //this is better from init function
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
}
在登录视图控制器
中MainViewController.sharedInstance?.writeValueBack(true)
答案 1 :(得分:1)
在MainViewController
中,您需要LoginController
实例的引用,可能需要IBOutlet
,然后在viewDidLoad
@IBOutlet weak var loginController : LoginController!
override func viewDidLoad() {
super.viewDidLoad()
loginController.mydelegate = self
}