为不同的设备调整 UItableview 的大小

Resizing UItableview For Different Devices

我有一个带有简单滚动条的视图控制器 table。它的尺寸为 320 x 340,位于显示屏的下半部分。

我想根据使用的设备调整它的大小。

我正在使用自动布局并设置高度约束:

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableHeightConstraint;

我没有看到任何会影响它的固定约束,我的头文件中有这个(它确实在模拟器中正确识别设备):

#define isiPhone6Plus ([[UIScreen mainScreen] bounds].size.height == 736)?TRUE:FALSE

我在 viewDidLoad 中有这个:

if(isiPhone6) {
    self.tableHeightConstraint.constant = (467);
    [self.tableView needsUpdateConstraints];
    NSLog(@"Height constraint%f",self.tableHeightConstraint.constant);
}

NSLog 显示值设置正确,但是 table 大小没有改变。我有其他设备的类似代码,但 table 不会移动。

欢迎提出任何想法,我在此站点上看到了其他建议,主要是针对似乎不相关的单元格高度。

覆盖 viewdidlayoutsubviews

- (void)viewDidLayoutSubviews
  {
      [super viewDidLayoutSubviews];
      self.tableHeightConstraint.constant = ([[UIScreen mainScreen] bounds].size.height)/2; // If your table view cover half the screen.
  }

使用自动版式时,我们会在此方法中执行所有与框架相关的更改。正确设置框架时调用 viewDidLayoutSubViews。

您需要在更新约束后调用 layoutIfNeeded

if(isiPhone6) {
    self.tableHeightConstraint.constant = (467);
    [self.tableView needsUpdateConstraints];
    NSLog(@"Height constraint%f",self.tableHeightConstraint.constant);

    [self layoutIfNeeded];         /// Add this
}