gpt4 book ai didi

swift - Swift 中不调用委托(delegate)方法?

转载 作者:可可西里 更新时间:2023-11-01 00:23:45 24 4
gpt4 key购买 nike

我想在不借助 segue 的情况下将一个 Bool 值从一个 View Controller 传递到另一个 View Controller 。所以我推荐并获得了委托(delegate)。

我已经在我的应用程序中申请了委托(delegate)。但是委托(delegate)方法没有被调用。我不知道我在哪里犯了错误。

所以请帮助我。

主视图 Controller

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)
}
}

第二 View Controller

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)
}

最佳答案

您没有初始化委托(delegate),也不需要,委托(delegate)通常用于异步回调。改为这样做:

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)
}
}
}

在登录 View Controller 中

MainViewController.sharedInstance?.writeValueBack(true)

关于swift - Swift 中不调用委托(delegate)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31783332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com