2016-09-13 66 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) 
相关问题