没有情节提要和segue的Swift委托问题

时间:2019-01-27 12:15:44

标签: ios swift delegates

我在另一个控制器中触发一个方法时遇到问题。我以编程方式设置了所有元素(按钮,视图。),我也使用了NavigationController

我希望每当新用户登录或注册时都触发fetchUsers()方法,以便tableView用当前正在填充Firebase的所有用户重新加载其单元格。

问题在于fetchUsersDelegate?.fetchUsers()的方法永远不会被调用,因为loginController.fetchUsersDelegate = self永远不会被设置为self并且总是保持为零。

所以我的问题是我应该如何正确设置fetchUsersDelegate

头等舱

class LoginController: UIViewController {

var fetchUsersDelegate: FetchUsersDelegate?

lazy var loginRegisterButton: UIButton = { 
    let button = UIButton()
    button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Register", for: .normal)
    button.setTitleColor(UIColor.white, for: .normal)
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
    button.layer.cornerRadius = 25
    button.layer.masksToBounds = true

    button.addTarget(self, action: #selector(handleLoginRegister), for: .touchUpInside)

    return button
}()

@objc func handleLoginRegister(){
    if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
        handleLogin()
    } else {
        handleRegister()
    }
}

func handleLogin() {

    guard let email = emailTextField.text, let password = passwordTextField.text else {
        print("Registration form is not valid")
        return
    }

    Auth.auth().signIn(withEmail: email, password: password) { (user, error) in

        if error != nil {
            print(error!)
            return
        }

        print("Sucessfully logged in")
        self.dismiss(animated: true, completion: nil)

    }

    self.fetchUsersDelegate?.fetchUsers()

}

第二堂课

class UsersController: UITableViewController, FetchUsersDelegate{


let cellID = "cellID"
var users = [User]()         
let loginController = LoginController()

override func viewDidLoad() {
    super.viewDidLoad()


    loginController.fetchUsersDelegate = self

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
    checkIfUserIsLoggedIn() 


}

func fetchUsers(){

    Database.database().reference().child("users").observe(.childAdded, with: { (DataSnapshot) in

        if let dictionary = DataSnapshot.value as? [String: AnyObject]{
            let user = User()
            user.name = dictionary["name"] as? String
            user.email = dictionary["email"] as? String
            self.users.append(user)

            // if we call just tableView.reloadData the app will crash, insead we need to call it inside
            // DispatchQueue.main.async

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        }

    }, withCancel: nil)

}

协议

protocol FetchUsersDelegate {
    func  fetchUsers()
}

*编辑:

这是我在AppDelegate类中设置rootViewController的方式

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    window?.rootViewController = UINavigationController(rootViewController: UsersController())

    return true
}

这就是我呈现LoginController的方式,如果有帮助,则handleLogout()方法位于UsersController内。

@objc func handleLogout(){

    do{
        try Auth.auth().signOut()
    } catch let logoutError{
        print(logoutError)
    }

    let loginController = LoginController()
    present(loginController, animated: true, completion: nil)

}

1 个答案:

答案 0 :(得分:0)

此行

let loginController = LoginController()

是问题,它与所显示的vc无关,并且是一个新的单独实例,因此当您呈现用户时

let user  = UsersController()
self.fetchUsersDelegate = user
present// add child// user

如果用户可以同时登录,并且表中存在用户表,那么我希望它是菜单列表或子vc