How do I select a UITableViewCell by default?

前端 未结 7 2088
忘了有多久
忘了有多久 2020-12-17 10:50

I have created a UITableView and would like a specific UITableViewCell to appear selected (blue) when the view is loaded.

相关标签:
7条回答
  • 2020-12-17 11:05

    Be judicious using this method, as selecting the row in this way is something Apple suggests against doing to show a "chosen" state.

    Instead, consider setting the cell's accessoryType property to something like UITableViewCellAccessoryCheckmark.

    0 讨论(0)
  • 2020-12-17 11:10
    -(void)viewWillAppear:(BOOL)animated {
        // assuming you had the table view wired to IBOutlet myTableView
        // and that you wanted to select the first item in the first section
        [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                                 animated:NO 
                           scrollPosition:UITableViewScrollPositionTop];
    }
    

    I'm using this technique to select one of two UITableViewCells so the users knows which cell a UIDatePicker below the table view it will effect. This technique is used by Apple in the calendar app when you create a new event and set the dates.

    0 讨论(0)
  • 2020-12-17 11:16

    Definitely watch out. I'm sure you have a good reason, but look closely at the Human Interface Guidelines document Apple provides. Apps get rejected for not unselecting table rows. I'd encourage you to find the appropriate section of the HIG and see Apple offers any suggestions.

    0 讨论(0)
  • 2020-12-17 11:18

    Use this code to select cell by default in table view, indexPath can be vary according to your need

    -(void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [theTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
    }
    
    0 讨论(0)
  • 2020-12-17 11:22

    Use the UITableViewCell method

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
    

    Info here.

    0 讨论(0)
  • 2020-12-17 11:24

    You should put it in viewWillAppear.

    [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                             animated:NO 
                       scrollPosition:0];
    

    If you try to select it in cellForRowAtIndexPath:, then it will not take the required style.

    0 讨论(0)
提交回复
热议问题