简体   繁体   中英

iOS - Reload element from table view cell

I'd like to implement a "like" functionality in a table view. Each row has a like button and a like counter.

When the user taps "like" the like counter should be increased by one. If the same user taps again, the like counter is decreased by one.

I have implemented this using reloadRowsAtIndexPaths . However, this reloads the whole cell and it is bad in terms of usability.

Would you know a simple mechanism to implement such a functionality? The main requirement is that only the like counter is updated, not the whole cell or table.

Thanks in advance, Tiago

U don't need to reload a whole cell, simply change the title/image for your like button.

Smth. like this:

#pragma mark - custom table cell

@interface TableCellWithLikeButton : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *userLikeButton;
@end
@implementation TableCellWithLikeButton
@end

#pragma mark - User modal
@interface User:NSObject
@property (assign, nonatomic) BOOL wasLiked;
@property (assign, nonatomic) NSInteger likesCounter;
@end

@implementation User
@end


@implementation VC1
{
    IBOutlet UITableView *_tableView;
    NSMutableArray *_users;
}

- (id)initWithCoder:(NSCoder*)aDecoder
{
    if(self = [super initWithCoder:aDecoder]) {
        _users = [NSMutableArray array];
        for (int i=0;i<100;i++) {
            User *user = [User new];
            [_users addObject:user];
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

}
#pragma mark - UITableViewDataSource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _users.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CellWithLikeButton";
    TableCellWithLikeButton *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    [cell.userLikeButton addTarget:self action:@selector(changeLikeStatus:) forControlEvents:UIControlEventTouchUpInside];
    User *user = _users[indexPath.row];
    [cell.userLikeButton setTitle:user.wasLiked?@"Liked":@"Like" forState:UIControlStateNormal];
    cell.userLikeButton.tag = indexPath.row;
    return cell;
}

- (void)changeLikeStatus:(UIButton *)likeButton
{
    User *user = _users[likeButton.tag];
    user.likesCounter += user.wasLiked?-1:1;
     user.wasLiked =  !user.wasLiked;
    [likeButton setTitle:user.wasLiked?@"Liked":@"Like" forState:UIControlStateNormal];
}
@end

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