[英]Accessing a UIButton in a custom UITableViewCell
我很困惑。
在我的cellForRowAtIndexPath方法中,我試圖設置UIButton標題:
無法運作:
cell?.react?.setTitle("\(currentObject.likes)", forState: UIControlState.Normal)
其中react
是一個UIButton,它是我的UITableViewCell子類的子視圖。
我似乎根本無法更新UIButton的標題。 我發現修改它的唯一方法是通過UITableViewCell子類中的UITapGestureRecognizer,
工作方式:
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)
}
}
創建一個自定義單元格(例如myCell),將按鈕添加為@IBOutlet,然后鍵入以下內容: let cell = tableView.dequeueReusableCellWithIdentifier("yourIdentifier", forIndexPath: indexPath) as! myCell
let cell = tableView.dequeueReusableCellWithIdentifier("yourIdentifier", forIndexPath: indexPath) as! myCell
。
我認為您的問題是您尚未將按鈕鏈接到單元格,而XCode不知道您在談論哪個按鈕。
您應該首先通過傳遞給您的方法的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
)設置一個標識符。
//嘗試這樣,首先在表格單元格中為該按鈕提供標簽
(cell?.contentView.viewWithTag(tag) as? UIButton)?.setTitle("\(currentObject.likes)", forState: UIControlState.Normal)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.