简体   繁体   中英

Objective c - proper way to set subview frame so it will fill the screen

I have a viewController inside of a navigationController , the view controller has a tableview.
In viewDidLoad I set the tableview

- (void)viewDidLoad
{
    [super viewDidLoad];

    // init tableView
    CGRect tableFrame = self.view.bounds;

    _tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];

    _tableView.delegate = self;
    _tableView.dataSource = self;

    [self.view addSubview:_tableView];
}

The problem with this code is that the table view frame is not correct - the height is 460 and I need it to be 416.

[The iPhone screen height is 480, minus the status bar (20) minus the navigation bar (44) = 416]

So what is the proper way to set the table view so it will fill the screen?
I can think of two ways:

  1. set its frame to = (0, 0, 320, 416)

  2. use: [_tableView setAutoresizingMask:(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)];

Don't use magic numbers. Use the resizing flags correctly. So yes, your 2. approach is correct.

1) Use the superviews bounds.
_tableView.frame = self.view.bounds; ;

2) Set autoresizing flags
[_tableView setAutoresizingMask: UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];

(you did all of this already :)

Number 1 is absolutely the wrong way to do it... what happens if the screen size changes in a future OS / device?

I'm curious why you're not doing this using a nib file, and saving yourself the trouble, but if you must do it in code, set the auto-resizing mask per your option 2.

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