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可以更改,那么協議/代理可能會更有效。

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
}
}
- 3 回答
- 0 關注
- 991 瀏覽
添加回答
舉報