天天看点

iOS如何利用UITableView实现单选效果

众所周知,iOS没有单选的控件,那么我们如何在ios上实现单选的效果呢?通过查资料我发现,可以通过改装下UITableView的多选,从而实现单选。

首先将UITableView设为多选模式

_tableView.allowsMultipleSelectionDuringEditing = YES;
    [_tableView setEditing:YES animated:YES];
           

 那么如何实现单选呢,当然就是在用户选中某一行的时候,把他上一行选中的效果删掉就可以啦!具体要在下面的回调函数中增加如下代码。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消前一个选中的,就是单选啦   
   //_index设为全局变量出初始化为-1,
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_index inSection:0];
    UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastIndex];
    lastCell.accessoryType = UITableViewCellAccessoryNone;
    
    // 选中操作
    UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
//    
//    // 保存选中的行
    _index = indexPath.row;
    //afterDelay为延迟多少删除上次的选中效果
    [_tableView performSelector:@selector(deselectRowAtIndexPath:animated:) withObject:lastIndex afterDelay:.0];
}