简体   繁体   中英

UIButton not changing on selected state

I am trying to make a simple UIButton that changes background image every time it is clicked. This is the code:

UIButton *likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[likeButton addTarget:self
               action:@selector(likeButtonPressed:)
     forControlEvents:UIControlEventTouchUpInside];
[likeButton setBackgroundImage:[UIImage imageNamed:@"icon-like-grey.png"] forState:UIControlStateNormal];
[likeButton setBackgroundImage:[UIImage imageNamed:@"icon-dislike-color.png"] forState:UIControlStateSelected];

.

- (IBAction)likeButtonPressed:(UIButton *)sender {
    if (sender.isSelected) {
        [sender setSelected:NO];
        NSLog(@"not selected");
    } else {
        [sender setSelected:YES];
        NSLog(@"selected");
    }
}

Apparently it gets selected the first time, and the button turns from grey to color. However, it then does not turn back to grey after it has been clicked a second time. The NSLog shows the correct code, so the problem must be on the [sender setSelected: ] line. What am I doing wrong?

EDIT:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    NSLog(@"in nil");
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

mainDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

cell.textLabel.text = @"Text";
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18];

        if (indexPath.row == 0) {
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.text = [NSString stringWithFormat:@"%@", [mainDelegate.imagesDescription objectAtIndex:indexPath.section]];

        } else if (indexPath.row == 1) {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [mainDelegate.imagesURL objectAtIndex:indexPath.section]]];
            cell.accessoryType = UITableViewCellAccessoryNone;

            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            [manager downloadWithURL:url
                                  options:0
                                 progress:^(NSUInteger receivedSize, long long expectedSize) {

                                 }
                                completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {

                                    if (image && finished) {
                                        cell.imageView.image = image;
                                    }
                                }
             ];

            UIButton *likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [likeButton addTarget:self
                           action:@selector(likeButtonPressed:)
                 forControlEvents:UIControlEventTouchUpInside];

            [likeButton setBackgroundImage:[UIImage imageNamed:@"icon-like-grey.png"] forState:UIControlStateNormal];
            [likeButton setBackgroundImage:[UIImage imageNamed:@"icon-dislike-color.png"] forState:UIControlStateSelected];

            likeButton.frame = CGRectMake(215, 60, 40, 40);
            likeButton.layer.borderWidth = 0;
            cell.textLabel.text = @"";

            [cell addSubview:likeButton];


        } else if (indexPath.row == 2) {

            NSString *location = [mainDelegate.imagesLocation objectAtIndex:indexPath.section];
            cell.textLabel.text = location;

            UILabel *labelRight = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 100, 100)];
            labelRight.textAlignment = NSTextAlignmentRight;

            labelRight.text = [NSString stringWithFormat:@"%@ %@", [mainDelegate.imagesLikes objectAtIndex:indexPath.section], @"Likes"];
            cell.accessoryView = labelRight;
        }

return cell;

}

You're adding a subview for your like button every time a cell gets dequeued, rather than just updating button's state. In this case a good practice is to subclass the UITableViewCell class and init it there, updating button's state from the tableView:cellForRowAtIndexPath: . Though this will require you to store button states elsewhere as a datasource (and to update them in your likeButtonPressed: method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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