Automatically add a UITableView with automatic autoruns

When I add a UITableView programmatically and use Autolayouts, I usually write code like this:

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)
                                                           style:UITableViewStylePlain];
[self.view addSubview:self.tableView];
self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = @{@"tableView": self.tableView};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tableView]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[tableView|"
                                                                  options:0
                                                                  metrics:nil
                                                                    views:views]];

The default initializer for UITableView requires that CGRect be included, but when we use AutoLayout, there is no need to install program code.

  • Is it correct to add a UITableView?
  • Is there a way to avoid the “dummy” CGRect?
+4
source share
1 answer

try it

self.tableView = [[UITableView alloc] initWithFrame:CGRectZero];
+4
source

All Articles