简体   繁体   中英

UITableViewCell button doesn't show selected or deselected state until scroll

I am working on application with a "like" button in its uitableviewcell, however the state of the cell doesnt show unless the uitableview is scrolled and the cell is off the screen and reappeared. Here is how I am attempting to display the button:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"ProfileCell";
    PFObject *data = self.posts[indexPath.row];
    NSLog(@"Data: %@", data);

    ProfileTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil)
    {


        cell = [[ProfileTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:MyIdentifier];


    }

    for(UIView *view in cell.contentView.subviews){
        if ([view isKindOfClass:[UIView class]]) {
            [view removeFromSuperview];
        }
    }

#pragma mark - Heart Button
    heartButton = [[UIButton alloc] init];
    [heartButton setImage:[UIImage imageNamed:@"heartButton"]
                 forState:UIControlStateNormal];
    [heartButton setImage:[UIImage imageNamed:@"heartButtonSelected"]
                 forState:UIControlStateSelected];
    dispatch_async(dispatch_get_main_queue(), ^ {
        PFQuery *query = [PFQuery queryWithClassName:@"OrganizationLike"];
        [query whereKey:@"Post" equalTo:data];
        [query whereKey:@"liker" equalTo:[PFUser currentUser]];
        [query getFirstObjectInBackgroundWithBlock:^(PFObject * _Nullable object, NSError * _Nullable error) {
            if (!object) {
                [heartButton setSelected:NO];
            }else{
                [heartButton setSelected:YES];
            }
        }];

    });
    [heartButton addTarget:self action:@selector(heartButton:) forControlEvents:UIControlEventTouchDown];
    [heartButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [cell.contentView addSubview:heartButton];


    [heartButton autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:80];
    [heartButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:7.0];
    [heartButton autoSetDimension:ALDimensionHeight toSize:15];
    [heartButton autoSetDimension:ALDimensionWidth toSize:16];

    PFQuery *lquery = [PFQuery queryWithClassName:@"OrganizationLike"];
    [lquery whereKey:@"Post" equalTo:data];
    [lquery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (objects.count>0) {
            UILabel *likeLabel = [[UILabel alloc] init];
            [likeLabel setNeedsDisplay];
            [likeLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
            likeLabel.backgroundColor = [UIColor clearColor];
            likeLabel.textColor = [UIColor colorWithRed:0.643 green:0.655 blue:0.667 alpha:1];
            likeLabel.font = [UIFont fontWithName:@"OpenSans-Light" size:8.881];
            likeLabel.textAlignment = NSTextAlignmentCenter;
            likeLabel.text = [NSString stringWithFormat:@"%d", objects.count];
            [likeLabel setNeedsDisplay];
            [cell.contentView addSubview:likeLabel];

            [likeLabel autoAlignAxis:ALAxisHorizontal toSameAxisOfView:heartButton withOffset:0];
            [likeLabel autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:heartButton withOffset:3];
        }
    }];

    return cell;
}

Here is how a button tap is handled:

- (void)heartButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        NSIndexPath *i=[self indexPathForCellContainingView:sender.superview];
        PFObject *data = self.posts[i.row];
        PFQuery *query = [PFQuery queryWithClassName:@"OrganizationLike"];
        [query whereKey:@"Post" equalTo:data];
        [query whereKey:@"liker" equalTo:[PFUser currentUser]];
        [query getFirstObjectInBackgroundWithBlock:^(PFObject * _Nullable object, NSError * _Nullable error) {
            if (!object) {
                PFObject *like = [PFObject objectWithClassName:@"OrganizationLike"];
                like[@"liker"] = [PFUser currentUser];
                like[@"Post"] = data;
                [like saveInBackground];
                [self.tableView reloadData];
            }
        }];
    } else {
        NSIndexPath *i=[self indexPathForCellContainingView:sender.superview];
        PFObject *data = self.posts[i.row];
        PFQuery *query = [PFQuery queryWithClassName:@"OrganizationLike"];
        [query whereKey:@"Post" equalTo:data];
        [query whereKey:@"liker" equalTo:[PFUser currentUser]];
        [query getFirstObjectInBackgroundWithBlock:^(PFObject * _Nullable object, NSError * _Nullable error) {
            [object deleteInBackground];
            [self.tableView reloadData];
        }];
    }
}

选择或更新布局显示后重新加载表格视图

First of all try by calling [self.tableView reloadData] in main thread.

Second check if [self.tableView reloadData] gets called. You can check by adding breakpoints.

Rather than reloading the whole tableView cell, you can reload tableView at specific indexpath by calling

[self.tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:nil];

check this this might work,

in - (void)heartButton:(UIButton *)sender

get updated object first and replace it in your main array object [self.posts replaceObjectAtIndex:index withObject:newObj];

Than use [self.tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:nil];

And more suggestion there are no need to remove all object first from cell view and than create new in cellForRowAtIndexPath: method instead just check if view object is already exist than just update its value/property

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