UITableViewCell不断取消选择

cor*_*ban 2 iphone objective-c uitableview ios

我对UITableView有一个奇怪的问题:我的tableview显示了用户可以从中选择一个对象的名称.该值已保存.当tableview出现时,选择该行(在cellForRowAtIndexPath中).但是在viewWillAppear中,首先选择行然后取消选择.您可以看到它是第一次被选中,因为蓝色背景会在短时间内发生.

我已经设定

self.clearsSelectionOnViewWillAppear = NO;

但这不起作用.请有人帮帮我!提前致谢.

这里有一些示例代码:

#import "ECTESTTableViewController.h"

@interface ECTESTTableViewController ()

@end

@implementation ECTESTTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.clearsSelectionOnViewWillAppear = NO;

}

#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 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //cell.backgroundColor = [UIColor redColor];
    }

    if (indexPath.row == 1)
    {
        //        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        NSLog(@"select %d", indexPath.row);
        cell.selected = TRUE;
    }
    else {
        //        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selected = FALSE;
    }

    cell.textLabel.text = [NSString stringWithFormat:@"row %d", indexPath.row];
    return cell;
}

@end
Run Code Online (Sandbox Code Playgroud)

Mik*_*ard 6

如果要以编程方式选择使用中的行UITableView:

- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition

不要设置selected单元格的状态.