如果调用reloadData
,则选定的UITableViewCell
不会保持高亮显示。所以我必须记住所选单元格的NSIndexPath
(无多选)。但如果我想在cellForRowAtIndexPath
中使用setHighlighted
,则该单元格不会高亮显示。若我在UITableViewController
的方法中这样做,那个么单元格就会高亮显示!?
除了这个问题,我还经历了另一件事。如果我将setHighlighted
与"正常"选择一起使用,使两个单元格同时高亮显示(这是不应该的),我会得到一种多选。我试图用deselectRowAtIndexPath
撤消高亮显示,但没有任何作用。它只在具有当前索引路径的didSelectRowAtIndexPath
中工作,或者在UITableViewController
的方法中只在之后与reloadData
一起工作。
我在iOS 7和iOS 8上遇到过这种情况。这是一个示例代码:
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"testCell"];
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(refreshPropertyList:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidLayoutSubviews
{
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
}
-(void)refreshPropertyList:(UIBarButtonItem *)sender {
[self.tableView reloadData];
NSIndexPath *temp = [NSIndexPath indexPathForRow:0 inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:temp];
[cell setHighlighted:true];
self.selectedIndexPath = temp;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"testCell" forIndexPath:indexPath];
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
cell.textLabel.text = @"Test";
if ([indexPath isEqual:self.selectedIndexPath]) {
[cell setHighlighted:YES];
}
else {
[cell setHighlighted:NO];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.tableView deselectRowAtIndexPath:self.selectedIndexPath animated:false];
self.selectedIndexPath = indexPath;
}
UITableViewCell
如何在reloadData
之后仍保持高亮显示?
您可以使用一行代码来选择一行
[self.tableView selectRowAtIndexPath:self.selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
选定和高亮显示是不同的。因此,您无法取消选择高亮显示的状态。访问:https://developer.apple.com/library/ios/documentation/uikit/Reference/UITableViewCell_Class/index.html#//apple_ref/occ/instm/UITableViewCell/setSelected:animated: