2016年4月13日 星期三

Update UITableViewCell from itself

The code that can update the cell itself.
// update UI on main thread
dispatch_async(dispatch_get_main_queue(), ^{
    //set cell need update
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [self setNeedsLayout];
    [self layoutIfNeeded];
    //trying to get the tableview
    id view = [self superview];
    // different level of UITableView wrapping in different iOS version,
    // for more detail please see:
    //  stackoverflow 
    while (view && [view isKindOfClass:[UITableView class]] == NO) {
        view = [view superview];
    }
    
    if (view) {
        UITableView *tableView = (UITableView *)view;
        NSIndexPath *indexPath = [tableView indexPathForCell:self];
        if (indexPath) {
            [tableView reloadRowsAtIndexPaths:@[indexPath] 
                             withRowAnimation:UITableViewRowAnimationNone];
        }
    }
});

沒有留言:

張貼留言