亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

問題檢測按鈕cellForRowAt

問題檢測按鈕cellForRowAt

慕虎7371278 2020-02-02 15:01:34
我需要檢測是否在UITableViewController中單擊了按鈕override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let LikesBtn = cell.viewWithTag(7) as! UIButton}
查看完整描述

3 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

Swift中最簡單,最有效的方法是回調閉包。


子類UITableViewCell,用于標識UI元素的viewWithTag方法已過時。

將自定義單元格的類設置為子類的名稱,并ButtonCellIdentifier在Interface Builder 中將標識符設置為。


添加一個callback屬性。


添加一個動作并將按鈕連接到該動作。


class ButtonCell: UITableViewCell {


    var callback : (()->())?


    @IBAction func buttonPressed(_ sender : UIButton) {

       callback?()

    }

}

在cellForRow回調分配到自定義單元格。


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellIdentifier", for: indexPath) as! ButtonCell

     cell.callback = {

         print("Button pressed", indexPath)  

     }

     return cell

  }

當按下按鈕時,將調用回調。索引路徑被捕獲。


編輯


如果可以添加或刪除細胞,則有一個警告。在這種情況下,通過從數據源數組獲取當前索引來更新索引路徑


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCellIdentifier", for: indexPath) as! ButtonCell

     let item = dataSourceArray[indexPath.row]

     // do something with item

     cell.callback = {

         let actualIndexPath = IndexPath(row: dataSourceArray.index(of: item)!, section: indexPath.section)

         print("Button pressed", actualIndexPath)  

     }

     return cell

  }

如果甚至section可以更改,那么協議/代理可能會更有效。


查看完整回答
反對 回復 2020-02-02
?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

這是我用的:


首先初始化按鈕作為Outlet和其action上的TableViewCell


class MainViewCell: UITableViewCell {


@IBOutlet weak var testButton: UIButton!


@IBAction func testBClicked(_ sender: UIButton) {


    let tag = sender.tag //with this you can get which button was clicked 


}




}

然后在您的主控制器中的cellForRow函數中,像這樣初始化按鈕的標簽:


class MainController: UIViewController, UITableViewDelegate, UITableViewDataSource, {


     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MainViewCell



        cell.testButton.tag = indexPath.row        


        return cell

    }


}


查看完整回答
反對 回復 2020-02-02
  • 3 回答
  • 0 關注
  • 991 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號