代码之家  ›  专栏  ›  技术社区  ›  FRIDDAY

如何通过单击带有UITableViewCell类的.xib文件中的按钮来传输UIViewController?

  •  0
  • FRIDDAY  · 技术社区  · 7 年前

    我有一个 UIViewController 几乎没有 TableViews UITableViewCell . 其中一个单元格有一个用于注销的按钮。

    我需要的是:当我点击按钮时,传输 viewController 另一种观点是 loginViewController

    问题是:我无法访问 storyboard navigationController 在我的 tableViewCell 班级((如下所示)

    class ProfileCell: UITableViewCell {
    
        override func awakeFromNib() {
            super.awakeFromNib()
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
        }
    
        @IBAction func btnLogout(_ sender: Any) {
    
        //here I want to navigate to another view.
    
           //below is a sample when I use in viewController classes. but how to use it inside this class.
    
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginID") as! LoginViewController
            self.navigationController?.present(vc, animated: true, completion: nil)
        }
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Amit    7 年前

    你可以试试 closure 要做到这一点,也需要:

    tableViewCell :

    class ProfileCell: UITableViewCell {
    
        var callBackOnButtonLogout: (()->())?
    
        override func awakeFromNib() {
            super.awakeFromNib()
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
        }
    
        @IBAction func btnLogout(_ sender: Any) {
            self.callBackOnButtonLogout?()
        }
    }  
    

    然后在你的 cellForRowAt 方法:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier", for: indexPath) as! ProfileCell
    
        cell.callBackOnButtonLogout = {
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginID") as! LoginViewController
            self.navigationController?.present(vc, animated: true, completion: nil)
        }
    
        return cell 
    } 
    
        2
  •  2
  •   Francesco Deliro    7 年前

    可以使用与视图控制器通信 delegation pattern :

    例如:

    protocol LogoutDelegate: class {
        func shouldLogout()
    }
    
    class ProfileCell: UITableViewCell {
    
        weak var logoutDelegate: LogoutDelegate?
    
        override func awakeFromNib() {
            super.awakeFromNib()
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
        }
    
        @IBAction func btnLogout(_ sender: Any) {
            logoutDelegate?.shouldLogout()
        }
    
    }
    

    然后必须在视图控制器中采用协议并设置 cell.logoutDelegate = self .