繁体   English   中英

无法更改UItableviewcell按钮的图像

[英]Unable to change the image of UItableviewcell Button

我在每个单元格中使用带有复选框按钮的UITableView。 当用户点击该单元格或按钮时,该按钮的图像必须更改为“选定”图像。 但是,当我点击任何单元格或按钮时,图像不会改变。

这是我的表格代码:

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)
}

在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返回indexPath上当前加载的单元格

您需要在按钮回调中的cellForRowAtIndexPath方法中的按钮复选框中添加目标,才能更改图像。 像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM