How to highlight a row in a UITableView

前端 未结 6 1133
名媛妹妹
名媛妹妹 2020-12-31 10:00

The code below seems to have no effect. I want it to be highlighed in the same way it highlights when you tap on a row

- (UITableViewCell *)tableView:(UITab         


        
6条回答
  •  天命终不由人
    2020-12-31 10:47

    As others have noted, you can programmatically select a cell using this method:

     [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    

    However, you should be careful not to call this method too soon.

    The first time that the view controller containing said tableView is initialized, the earliest that you should call this method is within viewDidAppear:.

    So, you should do something like this:

    - (void)viewDidAppear:(BOOL)animated
    {
       NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; // set to whatever you want to be selected first 
       [tableView selectRowAtIndexPath:indexPath animated:NO  scrollPosition:UITableViewScrollPositionNone];
    }
    

    If you try putting this call into viewDidLoad, viewWillAppear:, or any other early view lifecycle calls, it will likely not work or have odd results (such as scrolling to the correct position but not selecting the cell).

提交回复
热议问题