3

I have a button in a tableview cell. I want that initially the button has an image "A", when the user clicks on it, it changes to "B", when the user clicks on it again it changes back to "A".

Let the two images be "A" and "B" in this scenario I am unable to use tag because I am using it to determine which button the user clicked using indexPath.row

below is the current state of my button function.

@IBAction func setNotification(sender: UIButton!) {

        cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: sender.tag, inSection: 0)) as! CustomTableViewCell

        sender.setImage(UIImage(named: "B")!, forState: .Normal)
currentRegion = CLCircularRegion(center: CLLocationCoordinate2D(latitude: latitude ,longitude:longitude), radius: 10, identifier: "xyz")

Also this is how my cellForRowAtIndexPathfunction looks

cell.notifybutton.addTarget(self, action: "setNotification:", forControlEvents: UIControlEvents.TouchUpInside)
        cell.notifybutton.setImage(UIImage(named: "A"), forState: UIControlState.Normal)
        cell.notifybutton.tag = indexPath.row
2
  • So what is not working now ? Commented Aug 13, 2015 at 8:44
  • @JulianM after the image is changed to "B", i want it to change back to "A" when the user taps the button again Commented Aug 13, 2015 at 8:45

3 Answers 3

7

You change button image without using tag follow this code.

Your cellForRowAtIndexPathfunction set two button image for different state

cell.notifybutton.setImage(UIImage(named: "A"), forState: UIControlState.Normal)
cell.notifybutton.setImage(UIImage(named: "B"), forState: UIControlState.Selected)
cell.notifybutton.selected = false //default A image display

the your button clicked method

@IBAction func setNotification(sender: UIButton!) {
    if (sender.selected)
    {
         sender.selected = false
    }
    else
   {
        sender.selected = true
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

you should use below code

- (void)btnChangeImage {
    UIButton *btn;

    if (btn.selected) {
        [btn setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
    } else {
        [btn setImage:[UIImage imageNamed:@"diselected.png"] forState:UIControlStateNormal];
    }
}

Comments

0

cell.notifybutton.setImage(UIImage(named: "A"), forState: UIControlState.Normal) cell.notifybutton.setImage(UIImage(named: "B"), forState: UIControlState.Selected) cell.notifybutton.selected = false //default A image display

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.