
Size Classes
系统定义了两个size class,regular和compact,来描述某一个视图的宽度和高度。
任何一个视图都可以采用以下的size class的组合使用
Regular width, regular height
Compact width, compact height
Regular width, compact height
Compact width, regular height
至于其他的变更,iOS会基于content area的size class来动态调整layout。例如,当垂直size class从紧凑高度转换成普通高度时候,这种情况往往产生于当用户旋转设备的情况下,从横屏转换成竖屏方向,tab bars这个时候就会变得更高。
Device Size Classes
设备的size classes,在不同的设备和屏幕尺寸上展现全屏效果会使用不同的size class。

其他尺寸追加描述

Multitasking Size Classes
多任务size classes
在ipad设备,当你的app运行在多任务配置时(比如分屏),size classes也同样会被使用。

Xcode 9新的SizeClass适配界面

具体的效果是可以为每一个单独的控件方便地设置横屏和竖屏下的不同的约束进行布局。
1. 首先选择任意设备类型,此处选择的是iphone x, 并且安放了一个label,并且同时没有设置任何的约束

然后在默认的情况下测试设置约束,此处设置成将label居中显示,下面是竖屏下的效果

下面是横屏下的显示效果

可以看到都默认居中显示了。
如果进行测试,分别设置横屏和竖屏下的不同的约束,那么就要首先选择对应的模式,让后点击 Vary for traits, 选择后修改对应横屏或者竖屏下的想要的约束,完成后选择 Done Varying 就可以生效了。让我们一起来看看效果
竖屏

修改竖屏下的约束

选择Done Varying使其生效
运行后你会发现,竖屏下呈现了刚刚修改过的约束的效果,但是横屏下依然是最初居中显示的效果

同样的方法可以设置横屏下想要的约束设置即可了,这个是不是很方便和简单呢?那么下面就实例解决常见的一个开发中的问题,比如播放列表,tableview要求在竖屏时最多展示x行,但是因为屏幕高度问题,在转换成横屏后要求展示成y行。如何实现呢?当然可以用代码控制,但是会非常的繁琐,因此可以尝试通过这种方式来实现,实例如下:
首先是最终完成的效果:
竖屏

横屏

实现的方式很简单,就在tableview设置行数的datasource方法中判断当前屏幕方向是横屏还是竖屏就可以了
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
return9;
}else{
return5;
}
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reusecell"];
if(cell ==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reusecell"];
}
cell.backgroundColor = [UIColor grayColor];
cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
returncell;
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
return40.0f;
}