iOS - 从表格视图单元格中重新加载元素

时间:2015-06-07 10:57:35

标签: ios objective-c swift

我想在表格视图中实现“喜欢”功能。每行都有一个类似的按钮和一个类似的计数器。

当用户点击“喜欢”时,类似的计数器应该增加1。如果同一用户再次点击,则类似计数器减1。

我已使用reloadRowsAtIndexPaths实现此功能。然而,这会重新加载整个单元格,并且在可用性方面很糟糕。

您是否知道实现此类功能的简单机制?主要要求是只更新类似的计数器,而不是整个单元格或表格。

提前致谢, 蒂亚戈

1 个答案:

答案 0 :(得分:0)

您不需要重新加载整个单元格,只需更改类似按钮的标题/图像。

不便。像这样:

#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
相关问题