2016-09-13 67 views
0

我很困惑。在自定義UITableViewCell中訪問UIButton

在我的cellForRowAtIndexPath方法,我想設置一個UIButton標題:

不工作:

cell?.react?.setTitle("\(currentObject.likes)", forState: UIControlState.Normal) 

其中react是一個UIButton,那是我的UITableViewCell子類的子視圖。

我似乎無法更新我的UIButton的標題。我發現修改它的唯一方法是通過UITapGestureRecognizer在我的UITableViewCell子類,

工作:

func reaction(button : UIButton) { 
    if button.imageView?.image == UIImage(named: "ic_favorite.png") { 
     button.setImage(UIImage(named: "ic_favorite_border.png"), forState: UIControlState.Normal) 
    } else { 
    button.setImage(UIImage(named: "ic_favorite.png"), forState: UIControlState.Normal) 
    } 
} 
+0

是'react'是你的按鈕?你爲什麼寫'反應是我定製細胞的一個子類?'? – Tj3n

+0

你在哪裏宣佈了反應的動作 –

回答

0

創建一個自定義單元格(說了myCell),添加按鈕作爲@IBOutlet,然後鍵入這let cell = tableView.dequeueReusableCellWithIdentifier("yourIdentifier", forIndexPath: indexPath) as! myCell

你的問題我認爲你沒有將按鈕鏈接到單元格& XCode不知道你正在談論哪個按鈕。

+0

反應就是按鈕名稱! – scott

+0

好吧,這不是理想的,但它的工作。我只是通過IB鏈接它,它工作。 – scott

0

您應該首先獲得對您的單元格的引用,並將cellForRowAtIndexPath傳遞給您的方法。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier", forIndexPath: indexPath) as! UIButton   
    // do anything with cell 
    return cell 
} 

記得設置一個標識爲您的表格視圖單元格(UITableViewCell)。

+0

關於你編輯舊帖子:請不要編輯舊帖子只是爲了刪除諸如「不客氣,請參閱:」[一名版主向我發出消息,表示我的編輯只會刪除「謝謝」等),而不鼓勵]( http://meta.stackoverflow.com/a/333096/3773011)「。 – Makyen

+0

似乎公平。感謝您指出。 – navit

0

//嘗試這樣,先給標記該按鈕在你的表格單元格

(cell?.contentView.viewWithTag(tag) as? UIButton)?.setTitle("\(currentObject.likes)", forState: UIControlState.Normal) 
相關問題