IBOutlet 在 ViewController 方法中始终为零,但在 IBAction 和 Viewdidload 中正常

IBOutlet always nil in ViewController methods but ok in IBAction & Viewdidload

我尝试访问 Viewdidload 和 IBAction 之外的一些 IBOutlet,但总是得到 nil 值。在 Viewdidload 和 IBAction 中,这些值都可以。我错过了声明或初始化某些东西的部分吗?

在viewdidload()之后修改了值,因为viewdidload是在IBAction中调用的。

视图是在故事板中创建的,来自 UINavigation 控制器。

connection table between ViewController and UIView:

loginServer方法被userCredential委托调用,如下:

protocol userCredentialDelegate {
    func didUpdateCredential (sender:String, credential: Bool?)
}

class userCredential: NSObject {

var delegate:userCredentialDelegate?
// self.delegate = ViewController() removed

func loginServer (name: String, pwd: String) -> Bool {
dispatch_sync(dispatch_get_main_queue())
     {
     self.delegate?.didUpdateCredential ("login", credential: credentialStatus)
     }
}

主控制器:

class ViewController: UIViewController, userCredentialDelegate  {

// set the shared instance
let user = userCredential.sharedInstance

@IBOutlet weak var incorrectCredentials: UITextField!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var logButton: UIButton!

@IBAction func logButton(sender: UIButton) {
    print (incorrectCredentials?.hidden)
    if logButton.titleLabel!.text == "Log Out" {
        user.logoutServer ()
    } else {
        user.loginServer(username.text!, pwd: password.text!)
    }
}

func didUpdateCredential (sender: String, credential: Bool?) {
    switch sender {
    case "login":
        if credential! {
            performSegueWithIdentifier("loginSegue", sender: self)
        } else {
            incorrectCredentials?.hidden = false
        }
    default: break
    }
    if let credentialResponse = credential {
        loginStatus = credentialResponse
        }
    }

var loginStatus: Bool = false {
    didSet {
        if loginStatus {
            incorrectCredentials?.hidden = true                    // always nil before, now ok
        } else {
            incorrectCredentials?.hidden = false                   // always nil before, now ok
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    user.delegate = self
    incorrectCredentials.hidden = true  // can work here
    user.getUserInfo ()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

connection table:

您需要在 viewDidLoad 函数中将委托设置为您的用户模型。 在做 user.getUserInfo() 之前先做 user.delegate = self

目前您在用户模型上创建了一个新实例,这与您实际加载无关ViewController。