簡體   English   中英

從UITableViewCell到ViewController的按鈕操作

[英]Button Action from UITableViewCell to ViewController

我正在嘗試實現Delegate方式,以便在從UITableViewCell到ViewController的按鈕上執行某些操作。 以下是我到目前為止的情況 -

TableViewCell:

protocol UserCellDelegate : class {
    func disableUser(cell: UserCell, button: UIButton)
}

class UserCell : UITableViewCell {

    @IBOutlet weak var userLabel: UILabel!
    @IBOutlet weak var userDescription: UILabel!

    @IBOutlet weak var writeOutUser: UIButton!

    weak var delegate: UserCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        writeOutUser.layer.cornerRadius = 5.0
    }


    @IBAction func disableUserButtonAction(sender: UIButton) {
        delegate?.disableUser(self, button: writeOutUser)  //self here I believe to be the cell 
    }


}

視圖控制器:

class UserDetailTableViewController : UIViewController, UserCellDelegate {
    override func viewDidLoad() {
      super.viewDidLoad()
      let userCell = UserCell()
      userCell.delegate = self
    }

    func disableUser(cell: UserCell, button: UIButton) {
      print("VC: User Disabled")
    }
}

這里的問題是,我的ViewController中的disableUser函數永遠不會被調用。 我究竟做錯了什么?

最好的方法是什么?

我已經提到了SO批准的答案 ,這就是我所遵循的,但沒有運氣。 任何幫助將不勝感激。 謝謝!!

你應該在cellForRowAtIndexPath設置你的單元格的delegate 。正如@vadian所說,在viewDidLoad中你不應該使用默認的初始化程序來初始化你的單元格,並且在viewDidLoad ,你的單元格的委托是nil。

使用init(style:reuseIdentifier)初始化您的單元格,或者在行方法的單元格中設置委托,因為無論如何您將初始化該方法中的單元格。

當你這樣做時:

let userCell = UserCell()
userCell.delegate = self

您設置的委托userCell的, 只有委托userCell 我確定表視圖中顯示的表視圖單元格不是 userCell

因此,您應該設置實際要在表視圖中顯示的單元格的委托,而不是設置userCell的委托。 創建要在表視圖中顯示的新單元格的最可能位置是tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)方法。

在該方法中,您必須具有以下內容:

let cell = ...
// setting properties of cell using the model
return cell

您只需要在返回之前添加此行:

cell.delegate = self

在你的代碼中, UserCell就像一個UIView 您忘記將userCell添加到當前控制器的視圖中。 如果你想使用UITableViewCell ,更好的方法是使用UITableView。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM