简体   繁体   中英

Changing accessoryView on highlight of UITableViewCell

I'm trying to get my UITableViewCell to change it's accessoryView on highlight. So the accessory is darker when highlighted. I've managed to make it work pretty well so far with one exception. When a cell is pressed it causes the cell to highlight but when that press is moved and the highlight is cancelled the accessoryView keeps its highlighted image.

Is there any way to detect if the highlight was cancelled so I can change the accessoryView back to what it should be? Would I need to create a subclass of UITableViewCell in order to accomplish this? Any help is greatly appreciated. Thanks!

Normal State: 正常细胞状态

Highlighted State 在此输入图像描述

After pressing and moving the touch (what I'd like to avoid): 在此输入图像描述

 - (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UIImageView *accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessoryDark.png"]];
    cell.accessoryView = accessoryView;
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UIImageView *accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessory.png"]];
    cell.accessoryView = accessoryView;
}

I tried reproducing your setup and what I found is that the indexPath being passed to didUnhighlightRowAtIndexPath included an NSNotFound row. So you might want to check that the cell you're getting in didUnhighlightRowAtIndexPath is non-nil. If it turns out that you're getting the wrong indexPaths passed to didUnhighlightRowAtIndexPath then I think we can chalk it up to a bug in the new API and you're going to want to use didSelectRow and didDeselectRow, or subclass UITableViewCell and watch for changes to the selected and highlighted states in your subclass.

Another thing you could try is to set the accessory view to

[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessory"] highlightedImage:[UIImage imageNamed:@"accessoryDark"]];

Then (in theory) the accessory view will automatically show the correct highlighted or not highlighted image based on the highlighted state of the cell, and you won't have to watch for those updates in your delegate methods.

Try using didSelectRow... and didDeselectRow... . You should also keep a ref to the index path of the selected cell. That way the scrolling would not mess up your cells (of course, in the cellForRow... you check whether the current cell is the selected one, and set the accessory view accordingly). Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM