UITableView didSelectRowForIndexPath,不动画选择和取消选中复选标记

时间:2011-10-21 17:32:19

标签: iphone uitableview

我之前已经这样做了,但我很难再次使用它。在任何情况下,在我的模型类中,我基本上都有一个字典,其中有两个用于排序的项目,我只希望一个值为YES,其他值为NO。我希望在UITableViewCell中选择项目以反映该项目并为选择和取消选择设置动画。所以在模型类中,我有这个方法只是将选择的另一个值更改为false:

- (void)setSingleSort:(NSString *)key {
    for (NSString *str in [_sortOrderDictionary allKeys]) {
        if (str != key) {
            [_sortOrderDictionary setObject:[NSNumber numberWithBool:NO] forKey:str];
        }
    }
}

然后我在didSelectRowForIndexPath方法中有这个片段:

NSUInteger row = [indexPath row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[cell setSelected:YES animated:YES];

NSString *key;
BOOL valueAtKey;
    key = [_sortCategoryList objectAtIndex:row];
    valueAtKey = [[dmgr.SortOrderDictionary valueForKey:key] boolValue];
    if (valueAtKey != YES) {
        [dmgr.SortOrderDictionary setObject:[NSNumber numberWithBool:!valueAtKey] forKey:key];
        [dmgr setSingleSort:key];
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;

        [tableView deselectRowAtIndexPath:_lastIndexPath animated:YES];
    }
    _lastIndexPath = indexPath;
    [tableView reloadData]; //Edited, added this to the end and it seems to work.  Don't know why it's needed though since the deslectRowAtIndexPath should animated, along with the setSelected:Animated: right?

2 个答案:

答案 0 :(得分:1)

我认为你的selectionStyle是原因。这通常是我这样做的方式。在cellForRowAtIndexPath方法中:

//create new or fetch dequeued cell
if((indexPath.row == self.indexPathOfCurrentValue.row) && (indexPath.section == self.indexPathOfCurrentValue.section))
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
     cell.accessoryType = UITableViewCellAccessoryNone;

然后在didSelectRowAtIndexPath方法中,执行以下操作:

[tableView deselectRowAtIndexPath:indexPath animated:YES];

//APP RELATED LOGIC GOES HERE

if(nil != self.indexPathOfCurrentValue)
     [[tableView cellForRowAtIndexPath:self.indexPathOfCurrentValue] setAccessoryType:UITableViewCellAccessoryNone];

self.indexPathOfCurrentValue = indexPath;
[[tableView cellForRowAtIndexPath:self.indexPathOfCurrentValue] setAccessoryType:UITableViewCellAccessoryCheckMark];

这通常是我需要在用户点击时勾选行并取消选中最后一个选定行的方法。显然,currentValue索引路径变量保存最新的复选标记的索引路径。

答案 1 :(得分:-1)

摆脱这条线:

cell.selectionStyle = UITableViewCellSelectionStyleNone;