When using Autosizing in iOS storyboard how to guarantee a UITableView's cells won't be partial

StackOverflow https://stackoverflow.com/questions/17863540

  •  04-06-2022
  •  | 
  •  

سؤال

I have a table view with row height 33 and height 363. When displaying on iPhone 5 none of the table cells I add are cut off, it ends nicely and id good. The autosizing looks like:

Autosizing on iPhone 5 screensize

Now the issue is when I try this on a 3.5inch iPhone 4 screen, the last table cell is half cut off because the height is now 275. I do want the tableview to shrink but I want the height to stay a multiple of 33.

I can think of two possible ways: 1) In storyboard set the small tableview to a correct height (say 297), then is there a way to set a max size on the autosizing via storyboard?

2)Programmatically detect iPhone type and adjust in code. What is the safest way to do this?

هل كانت مفيدة؟

المحلول

You can either do it in code by detecting the iPhone type like #2, or if you use layout constraints, you can add a single constraint in code that relates the height of the table view to the height of the screen. The table view height can be expressed as the screen height times a multiplier plus a constant, so if you solve for these two equations, you'll get values for the multiplier and constant that will work:

568 * multiplier + constant = 363 and 480 * multiplier + constant = 297

If you work this out, it gives you multiplier = .75 and constant = -63.0115

So the code I use looks like this. I add a fudge factor of 10 to the constant I calculated to take care of padding in the table view (I determined this empirically). I created a height constraint in IB, and made an IBOutlet to it -- it doesn't matter what its value is, since I immediately remove it in viewDidLoad (it's needed in IB so the constraints will be sufficient).

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.theData = @[@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine",@"Ten",@"Eleven",@"Twelve"];
    [self.tableView reloadData];
    [self.tableView removeConstraint:self.tableHeight];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeHeight relatedBy:0 toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.75 constant:-63.0115 + 10]];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top