2015-06-07 99 views
0

我想在表格視圖中實現「喜歡」功能。每行都有一個類似的按鈕和一個類似的計數器。iOS - 從表格視圖單元格重新加載元素

當用戶點擊「like」時,應該增加一個類似的計數器。如果同一用戶再次點擊,則類似計數器減1。

我已經使用reloadRowsAtIndexPaths實現了這一點。但是,這會重新加載整個單元,並且在可用性方面不好。

你知道一個簡單的機制來實現這樣的功能嗎?主要要求是隻更新類似的計數器,而不是整個單元格或表格。

由於提前, 蒂亞戈

+1

子類你的UITableViewCell和揭露重新加載只有相關意見的公共方法 – Shai

回答

0

ü不需要重新加載整個細胞,只需更改標題/形象,爲您喜歡按鈕。

Smth。像這樣:

#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:[email protected]"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:[email protected]"Liked":@"Like" forState:UIControlStateNormal]; 
} 
@end 
相關問題