2016-05-27 113 views
0

我在每個單元格中使用帶有複選框按鈕的UITableView。當用戶點擊該單元格或按鈕時,該按鈕的圖像必須更改爲「選定」圖像。但是當我點擊任何單元格或按鈕時,圖像沒有變化。無法更改UItableViewcell的圖像按鈕

這裏是我的表碼:

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

    let cell : categoryCell = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! categoryCell 
    let dic : NSDictionary = categoryitem.objectAtIndex(indexPath.row) as! NSDictionary 
    cell.category_name.text = dic.valueForKey("category_name") as? String 


    return cell 

} 


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return categoryitem.count 
} 
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

    let cell : categoryCell = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! categoryCell 

    cell.category_button.setImage(UIImage(named: "check_checkbox"), forState: UIControlState.Normal) 
    let dic : NSDictionary = categoryitem.objectAtIndex(indexPath.row) as! NSDictionary 
    print(dic.valueForKey("category_id") as! String) 
} 
+0

您是否在categoryCell中爲imageView創建了IBOutlet? –

+0

但我想更改uibutton的圖像。所以我創建了uibutton的iboutlet @SandeepBhandari –

+0

對不起,我的意思是UIButton:D –

回答

1

改變你在didSelectRowAtIndexPath方法代碼

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

    let cell : categoryCell = tableView.cellForRowAtIndexPath(indexPath) as! categoryCell 

    cell.category_button.setImage(UIImage(named: "check_checkbox"), forState: UIControlState.Normal) 
    let dic : NSDictionary = categoryitem.objectAtIndex(indexPath.row) as! NSDictionary 
    print(dic.valueForKey("category_id") as! String) 
} 

錯誤,你做

let cell : categoryCell = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! categoryCell 

將返回重複使用的電池,但你需要訪問當前加載電池在用戶點擊的indexPath處:)所以使用cellForRowAtIndexPath。 cellForRowAtIndexPath返回索引路徑中當前加載的單元格

+0

感謝男人它的一個時間savier。爲我工作。 –

+0

@ Jack.Right:永遠歡迎好友:) –

0

您需要在按鈕調用添加目標到您的按鈕複選框中的cellForRowAtIndexPath方法 回你可以改變圖像。這樣

[cell.checkButton addTarget:self action:@selector(buttonclick:) forControlEvents:UIControlEventTouchUpInside]; 
checkbutton.tag=indexpath.row; 
-(void)buttonclick:(id)sender 
{` 
// you can change your image here.. 
} 
+0

但我該如何訪問該功能中的按鈕? –

+0

像我如何定義細胞外的方法? –

+0

@ Jack.Right你得到的按鈕引用那裏作爲發件人 – user3306145