2014年2月24日 星期一

UITableView的單選機制

//先在class中宣告一個全域變數int _selectedIndex = 0;

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
     *  @單選機制
     */
    //取消前一個選取的
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
    UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
    //lastCell.accessoryType = UITableViewCellAccessoryNone;
    lastCell.accessoryView = nil;

//取消所有目前看的到的Cell的(可以取代上面的區塊)
NSArray *visibleCells = [tableView visibleCells];
    for(UITableViewCell *_eachCell in visibleCells)
    {
        //_eachCell.accessoryType = UITableViewCellAccessoryNone;
        _eachCell.accessoryView = nil;

    }
    
    //選取的
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //cell.accessoryType = UITableViewCellAccessoryCheckmark;
    cell.accessoryView = button;
    
    //存入這筆選到的
    _selectedIndex = indexPath.row;
    //0.5秒後移除cell被選取時的效果
    [tableView performSelector:@selector(deselectRowAtIndexPath:animated:) withObject:indexPath afterDelay:.5];

}

沒有留言:

張貼留言