![](/img/trans.png)
[英]How to get the indexPath.row when I click a button on a table view cell?
[英]How can I know which indexPath.row my button in when I press a button to push to another ViewController?
也許問題不夠清楚。
我的意思是我有一個TableView,它有一個Prototype Cell,這個Cell有一個按鈕。
我設置了一個名為“ForMore”的segue名稱,它組合了2個ViewControllers
但我多次重復使用這個Cell。
這是結果:
當我單擊所有單元格中的每個按鈕時,它將跳轉到另一個ViewController。
但我需要知道我點擊了哪個按鈕,因為ViewController需要根據我點擊的單元格進行初始化。
那么,當我多次重復使用單元格時,如何知道我單擊了哪個單元格。
使用自定義單元格執行任何操作的最佳方法是使用自定義類。
這樣,按鈕是類的屬性,操作可以發送到單元格。
這樣,您可以使用塊來自定義按鈕在創建時所執行的操作。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create the cell...
cell.buttonBlock = {
self.buttonTappedAtIndexPath(indexPath)
}
return cell
}
或類似的東西。
我曾經遇到過這個問題,我這樣做了。
// CustomCellClass
var tableViewdelegate: MyTableViewDelegateClass?
// button in cell action
@IBAction func buttonPressed(sender: AnyObject) {
tableViewdelegate?.buttonPressedInCell(cell: self)
}
// MyTableViewDelegateClass
func buttonPressedInCell(cell: CustomCellClass) {
let indexPath = tableView.indexPathForCell(cell)
// other logic you have
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = // create your cell or deque
cell.tableViewdelegate = self
return cell
}
我已經嘗試了上述所有方法,但沒有奏效。也許我無法理解答案。
但我自己解決了這個問題。
這就是我做的:
1,創建一個新類繼承名為'ForMore'的UIButton並聲明一個名為'row'的var
2,將ForMoreButton與名為'ForMoreButton'的自定義單元格相結合
3,當我在方法中創建單元格時,將indexPath.row分配給cell.ForMoreButton.row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
4,在ViewController中我的tableview里面,直接將ForMoreButton與這個ViewController結合使用'ButtonTapped'動作,然后我們可以從(發送者為!ForMore).row獲取行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.