问题
I am doing "Add to favourite Page" using SWIFT. In my product list table, "Wish" button is there. That button is dragged from Storyboard. If User clicks the button, that image change to another new one. I did upto this part, exactly working too. But, if we scroll the tableview, automatically another cell button image has been changed to new one. I don't know how and why? How to solve this? Kindly guide me.
//MY CODING IS BELOW
unc tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell1 = product_tableview.dequeueReusableCellWithIdentifier("productmain", forIndexPath: indexPath) as product_tblCell
image_url = arrayFromJson[indexPath.row].valueForKey("image_url") as NSString
let imgurl = NSURL(string: image_url)!
var imgdata : NSData = NSData(contentsOfURL: imgurl)!
prod_img = UIImage(data: imgdata)!
id = String(arrayFromJson[indexPath.row].valueForKey("id") as NSInteger)
code = arrayFromJson[indexPath.row].valueForKey("code") as NSString
descrip = arrayFromJson[indexPath.row].valueForKey("description") as NSString
name = arrayFromJson[indexPath.row].valueForKey("name") as NSString
price = String(arrayFromJson[indexPath.row].valueForKey("price") as NSInteger)
cell1.name.text = name
cell1.prod_desc.text = descrip
cell1.prod_price.text = price
cell1.prod_image.image = prod_img
cell1.wish_image_but.addTarget(self, action : Selector("to_wish_list:"), forControlEvents: UIControlEvents.TouchUpInside)
return cell1
}
func to_wish_list(sender : UIButton)
{
var img = UIImage(named: "wish_2.png")
sender.setImage(img, forState: UIControlState.Normal)
sender.enabled = false
}
回答1:
The reason is when you scroll the tableview and your cell goes beyond visible boundry, it is used for displaying another data. And when it has comes back is visible boundry it's data is set again.
That means, you have to check if the cell has been marked for "to_wish_list" while setting cell data. if yes then set the UIImage(named: "wish_2.png") by default else set defult image.
来源:https://stackoverflow.com/questions/29431538/uibutton-inside-uitableviewcell-facing-image-changing-issue-while-tableview-get