2016-08-25 34 views
0

我在表格裏面有custem單元格 裏面我有一個按鈕,我想當用戶點擊按鈕時推送viewController,我該怎麼做,以及如何知道該小區內的用戶使用它的按鈕,因爲這裏沒有didSelectRowAtIndexPathcellView裏面的按鈕我無法知道用戶按下了哪個單元格

+1

重複http://stackoverflow.com/questions/19000356/ios-7-how-to-get-the-indexpath-from-button-placed-in-uitableviewcell – JJBoursier

+0

@JJBoursier我希望在迅速,可以你爲我解釋一下嗎?我不知道關於objective-c – joda

回答

0

添加標籤,並添加目標的過渡功能

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

let cell =  tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! CustomCell 
cell.button.tag = indexPath.row 
cell.button.addTarget(self, action: #selector( self.transitonMethod ), forControlEvents: UIControlEvents.TouchUpInside) 
return cell 

} 

從發送按鈕的標籤取indexPath和取細胞這個indexPath.Push您的導航控制器上的控制器

func transitonMethod(sender: AnyObject){ 
let indexPath = NSIndexPath.init(index: sender.tag) 
let cell = tableView.cellForRowAtIndexPath(indexPath) 

self.navigationController?.pushViewController(yourController, animated: true) 

}

0

聲明一個IBAction爲如下的建議在IOS 7 - How to get the indexPath from button placed in UITableViewCell

@IBAction func didTapOnButton(sender: UIButton) { 
    let cell: UITableViewCell = sender.superview as! UITableViewCell 
    let indexPath: NSIndexPath = self.tableView.indexPathForCell(cell) 
    // Do anything with the indexPath 
} 

或者其他方法:

@IBAction func didTapOnButton(sender: UIButton) { 
    let center: CGPoint = sender.center 
    let rootViewPoint: CGPoint = sender.superview?.convertPoint(center, toView: tableView) 
    let indexPath: NSIndexPath = tableView.indexPathForRowAtPoint(rootViewPoint!) 
    print(indexPath) 
} 

然後使用該indexPath來執行任何您需要的操作。

+0

我在這個UItableViewCell類中寫的,但我得到錯誤,它說「沒有成員」tableView「 – joda

+0

你必須在包含TableView的ViewController中聲明此方法... ... 1 - UIButton在你的單元格中,添加約束條件; 2 - 在包含TableView的ViewController中聲明IBAction方法; 3 - 將按鈕鏈接到單元格,並且你在單元格的控制器內部任意圖形(如設置標題); 4發送事件到ViewController,你通過故事板聲明瞭IBAction; – JJBoursier

+0

@JJBoursier你的第一個方法是不安全的,因爲它依賴於tableViewCell的體系結構,它也是錯誤的,因爲'sender.superview'不會讓你細胞,它會讓你到'tableViewCellContentView'。去你需要去兩層的單元格,比如'(sender.superview)?superview' –

0

在的tableview的cellforRow方法:

1)設定按鈕的標籤例如yourButton.tag = indexpath.row

2)設置yourbutton egbuttonPressed的目標方法(發送者:在目標方法的UIButton)

3)現在,將得到indexpath.row通過sender.tag

2

創建一個自定義按鈕

class CustomButton: UIButton { 
    var indexPath: NSIndexPath! 
} 

在您的自定義單元格創建的CustomButton類型的按鈕添加以下行cellForRowAtIndexPath

cell.yourCustomButton.indexPath = indexPath 

定義IBAction像按鈕在細胞這個

@IBAction func customButtonClicked(sender: CustomButton) { 
    let indexPath: NSIndexPath = sender.indexPath 
    // Do whatever you want with the indexPath 
} 
+0

要訪問'sender.indexPath'發件人應該是CustomButton類型。 –

+0

已編輯。謝謝@SamM – Manish

相關問題