ios - 无法设置多个 Controller 的 UILabel 字段

标签 ios iphone swift

我可以通过 ViewController 验证用户登录。 Swift 并将 View 重定向到 DisplayDetailsViewController.swift,它只有一个名为 nameLabelUILabel

只要登录成功,我就会从 ViewController.swift 调用 DisplayDetailsViewController.swift 中的 loadValues(name: String) 函数> 在函数登录中。

每当我尝试设置nameLabel 的值时,我都会遇到错误。如果我尝试设置任何字符串,问题也是一样的。我想我无法找到正确的 UILabel

main.storyboard

  1. AppDegate.swift:

    //
    //  AppDelegate.swift
    //  AutoLayout
    //
    //  Created by BIKRAM BHANDARI on 11/1/17.
    //  Copyright © 2017 BIKRAM BHANDARI. All rights reserved.
    //
    
    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch.
            return true
        }
    
        func applicationWillResignActive(_ application: UIApplication) {
            // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
            // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        }
    
        func applicationDidEnterBackground(_ application: UIApplication) {
            // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
            // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        }
    
        func applicationWillEnterForeground(_ application: UIApplication) {
            // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        }
    
        func applicationDidBecomeActive(_ application: UIApplication) {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        }
    
        func applicationWillTerminate(_ application: UIApplication) {
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        }
    
    
    }
    
  2. ViewController.swift

        //
        //  ViewController.swift
        //  AutoLayout
        //
        //  Created by BIKRAM BHANDARI on 11/1/17.
        //  Copyright © 2017 BIKRAM BHANDARI. All rights reserved.
        //
    
        import UIKit
    
        class ViewController: UIViewController, UITextFieldDelegate{
    
    
            @IBOutlet var txtUsername: UITextField!
            @IBOutlet var txtPassword: UITextField!
            var passWordProtected: Bool = false;
    
            var loggedInUser:User?;
    
            private struct constants{
                //static var highlighted: UIControlState{ get {return }}
            }
            //--------------------------------------------------------------------------------------------------------------------------------//
            override func viewDidLoad() {
                super.viewDidLoad();
                txtUsername.delegate = self;
    
                let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap)); //Check the tap gesture to dissmiss the keyboard
                view.addGestureRecognizer(tapGesture)
            }
            //--------------------------------------------------------------------------------------------------------------------------------//
            @IBAction func Login() {
                if let loggedInUser = User.checkLoginCredentials(username: txtUsername.text ?? "" , password: txtPassword.text ?? ""){
    
                  let secondViewController: DisplayDetailsViewController = DisplayDetailsViewController();
                    self.present(secondViewController, animated: true, completion: nil);
                    self.performSegue(withIdentifier: "Display Details", sender: self);
    
                    txtUsername.text = "";
                    txtPassword.text = "";
    
                    let displayDetails = DisplayDetailsViewController();
                    displayDetails.loadValues(name: loggedInUser.name);
            }
        }
    func tap(gesture: UITapGestureRecognizer) { 
            txtUsername.resignFirstResponder();
            txtPassword.resignFirstResponder();
        }
    
            //--------------------------------------------------------------------------------------------------------------------------------//
            func textFieldShouldReturn(_ textField : UITextField) ->Bool{ //Function to change move to next text field when keyboard next is                            pressed
                if(textField == txtUsername){
                    txtPassword.becomeFirstResponder();
                }
                return true;
            }
    
            //--------------------------------------------------------------------------------------------------------------------------------//
            @IBAction func togglePasswordField(_ sender: UIButton) {        // Function to change the password field to secure or show the typed password
                if passWordProtected{
                    txtPassword.isSecureTextEntry = true;
                    sender.setImage(#imageLiteral(resourceName: "view"), for: UIControlState.normal)
                    passWordProtected = false;
    
                }else{
                    txtPassword.isSecureTextEntry = false;
                    sender.setImage(#imageLiteral(resourceName: "hide"), for: UIControlState.normal)
                    passWordProtected = true;
                }
            }
    
        }
    
  3. 用户.swift

    //
    //  User.swift
    //  AutoLayout
    //
    //  Created by BIKRAM BHANDARI on 15/1/17.
    //  Copyright © 2017 BIKRAM BHANDARI. All rights reserved.
    //
    
    import Foundation
    struct User{
        let name: String;
        let company: String;
        let username: String;
        let password: String;
    
        static func checkLoginCredentials(username: String, password: String) -> User?{
            if let user = database[username]{
                if user.password == password{
                    return user;
                }
            }
            return nil;
        }
    
        static let database: Dictionary<String, User> = {
        var theDatabase = Dictionary<String, User>()
        for user in [
            User(name:"Bikram", company:"Self Company", username:"bikram", password:"bhandari"),
            User(name:"Sabina", company:"No company till now", username:"Sabina", password:"Sabu"),
            User(name:"Mac", company:"Apple Inc. ", username:"iphone", password:"6plus"),
            User(name:"Samsunng", company:"Sumsung Inc.", username:"note", password:"7")
            ]{
                theDatabase[user.username] = user;
            }
            return theDatabase
        }();
    }
    
  4. DisplayDetailsViewController.swift

    //  DisplayDetailsViewController.swift
    //  AutoLayout
    //
    //  Created by BIKRAM BHANDARI on 15/1/17.
    //  Copyright © 2017 BIKRAM BHANDARI. All rights reserved.
    //
    import UIKit
    
    class DisplayDetailsViewController: UIViewController {
    
        @IBOutlet weak var nameLabel: UILabel!
    
        //***********************************//
        func loadValues(name: String){
            nameLabel.text = "Bikram";
        }
    
    }
    
  5. 更新 ViewController.swift

    //
    //  ViewController.swift
    //  AutoLayout
    //
    //  Created by BIKRAM BHANDARI on 11/1/17.
    //  Copyright © 2017 BIKRAM BHANDARI. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController, UITextFieldDelegate{
    
    
        @IBOutlet var txtUsername: UITextField!
        @IBOutlet var txtPassword: UITextField!
        var passWordProtected: Bool = false;
    
        var loggedInUser:User?;
    
        private struct constants{
            //static var highlighted: UIControlState{ get {return }}
        }
        //--------------------------------------------------------------------------------------------------------------------------------//
        override func viewDidLoad() {
            super.viewDidLoad();
            txtUsername.delegate = self;
    
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap)); //Check the tap gesture to dissmiss the keyboard
            view.addGestureRecognizer(tapGesture)
        }
        //--------------------------------------------------------------------------------------------------------------------------------//
        @IBAction func Login() {
            if let loggedInUser = User.checkLoginCredentials(username: txtUsername.text ?? "" , password: txtPassword.text ?? ""){
    
              let secondViewController: DisplayDetailsViewController = DisplayDetailsViewController();
                self.present(secondViewController, animated: true, completion: nil);
                self.performSegue(withIdentifier: "Display Details", sender: self);
    
                txtUsername.text = "";
                txtPassword.text = "";
    
                let displayDetails = DisplayDetailsViewController();
                displayDetails.user = loggedInUser;
        }
    }
        //--------------------------------------------------------------------------------------------------------------------------------//
        func tap(gesture: UITapGestureRecognizer) { //Function to dismiss the keyboard when it is pressed anywhere in the storyboard.
            txtUsername.resignFirstResponder();
            txtPassword.resignFirstResponder();
        }
    
        //--------------------------------------------------------------------------------------------------------------------------------//
        func textFieldShouldReturn(_ textField : UITextField) ->Bool{ //Function to change move to next text field when keyboard next is                            pressed
            if(textField == txtUsername){
                txtPassword.becomeFirstResponder();
            }
            return true;
        }
    
        //--------------------------------------------------------------------------------------------------------------------------------//
        @IBAction func togglePasswordField(_ sender: UIButton) {        // Function to change the password field to secure or show the typed password
            if passWordProtected{
                txtPassword.isSecureTextEntry = true;
                sender.setImage(#imageLiteral(resourceName: "view"), for: UIControlState.normal)
                passWordProtected = false;
    
            }else{
                txtPassword.isSecureTextEntry = false;
                sender.setImage(#imageLiteral(resourceName: "hide"), for: UIControlState.normal)
                passWordProtected = true;
            }
        }
    
    }
    
  6. 更新了 DisplayDetailsViewController

    //
    //  DisplayDetailsViewController.swift
    //  AutoLayout
    //
    //  Created by BIKRAM BHANDARI on 15/1/17.
    //  Copyright © 2017 BIKRAM BHANDARI. All rights reserved.
    //
    
    import UIKit
    
    class DisplayDetailsViewController: UIViewController {
    
        @IBOutlet weak var nameLabel: UILabel!
    
        var user: User!{
            didSet{
            nameLabel.text = user.name}
        }
        //***********************************//
    }
    

最佳答案

nameLabel 可能还没有被初始化,因为它还没有出现在屏幕上。

尝试在包含用户对象的 DisplayDetailsViewController 中创建一个 var。

代替:

displayDetails.loadValues(name: loggedInUser.name);

尝试:

displayDetails.user = loggedInUser; 
// assuming you have created a var in DisplayDetailsViewController
// called user of type User

然后在DisplayDetailsViewController的viewWillAppear中,添加你原来的代码行:

nameLabel.text = user.name

这个有用吗?

编辑

我有这个作为我的结构

struct User
{
    var name = ""
    var age = 0
}

在转换到下一个屏幕之前(在推送 View Controller 之前或准备 segue 之前),您需要实例化您的用户,例如我正在这样做:

覆盖 func prepare(对于 segue:UIStoryboardSegue,发件人:Any?)

let user = User(name: "Shawn", age: 26)        
let destination =  segue.destination as! DisplayDetailsViewController
destination.user = user

最后是 DisplayDetailsViewController:

class DisplayDetailsViewController: UIViewController {

    var user = User()

    @IBOutlet var label: UILabel!

    override func viewWillAppear(_ animated: Bool) {
        label.text = user.name
    }
} 

我运行它,我得到的标签在详细信息屏幕上成功显示了 Shawn

关于ios - 无法设置多个 Controller 的 UILabel 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672284/

相关文章:

iphone - [CFNumber 发布] : message sent to deallocated instance

iphone - 没有重复的问题应用程序

swift - CKSubscription 返回错误,即在使用 FiresOnce 时查询必须至少具有一种触发模式

ios - 高分辨率屏幕上的 UIButton 圆角半径

ios - 如何显示仅连接 2 个点的多段线?

ios - 框架仅在设备上导致崩溃

ios - 在 iOS 应用程序中存储用户信息的最佳方式

ios - Firebase Unity Google-services-info.plist iOS无法正常运行

ios - 在继续循环之前让后台任务完成

ios - 与委托(delegate)的内存管理?