开发中:要进行适配
什么是适配:
适应、兼容不同的情况
常见的适配:
1.系统适配:针对不同版本的操作系统进行适配
2.屏幕适配:针对不同大小的屏幕尺寸进行适配
iOS屏幕适配:
iPhone尺寸:3.5inch、4.0inch、4.7inch、5.5inch
iPad尺寸:7.9inch、9.7inch
屏幕方向:横屏、竖屏

1、Autoresizing:
使用前提关掉AutoLayout

1、横竖屏幕相对简单
2、让子控件跟随父控件的尺寸发生相应的变化
3*、处理父子关系---在storyboard中实现的,无法实现兄弟控件的布局


代码实现Autoresizing(iPad)
这个代码其实很恶心 —设置谁,谁就不固定(设置顶部不固定,那么底部就是固定的)(只有宽高是设置就固定。。。)

Xcode预览功能:(可以预览在不同情况下的屏幕效果)

2、AutoLayout(自动布局)
用来布局UI界面的
iOS6.0(xcode4.0)就出现了(iPhone5)
iOS7.0(xcode5.0)流行Autolayout (iPhone5s)
任何控件都可以产生联系,可以很轻松解决屏幕适配的问题
核心:
参照
:你相对于谁来说
约束
:你距离谁来说之间有多少间距(宽度约束,高度约束)
在父控件垂直居中,水平居中就可以勾选

UILable在AutoLayout的具体实现
1、在没有AutoLayout情况下文字内容是处置居中的,所以导致上面与下面又间距
2、有AutoLayout设置约束,只需要设置lable的宽度和距离父控件的左边,顶部,就可以自动包裹内容。
但是如果改变文字后,让Lable的宽度包裹

Less than or equal :
让它的宽度小于等于设置的宽度,也就是根据lable的内容自动拉伸

举几个小例子
让父控件的高度跟随子控件的内容进行伸缩

** 效果图展示:**

结论:根据UILable的内容大小,去调整控件的大小
1、设置父控件的约束 内部错误:注:(2.距离控制器View的左边)

**上述设置完后是显示红色的约束不完整**
** 2.设置内部的ImageView的约束**

** 3.设置Lable 约束**

此处省略下面View的约束
** 4.做完后,发现约束好了,这时候更新约束,效果就出来了**
总结:不要设置父控件的高度,根据内部的控件来计算高度。
第二种思路:
1、删除UILable距离父控件底部的约束(这条线决定父控件的高度拉伸)

2、先设置让黄色的View距离UILable的顶部
(后面更换因为Bottom和Top都在同一种类型里面)

3、反转,让父控件距离内部控件

4、设置黄色View的底部=UILable的底部+20

新需求:
当我点击屏幕的时候,让黄色的View与橘黄色的View之间有50的间距

这个时候只需要拥有这个属性,
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 取出结构体
CGRect frame = self.orangeView.frame;
frame.origin.y +=60;
// 修改后,再覆盖回去
self.orangeView.frame = frame;
}
iOS建议:忘掉Frame,使用Autolayout
引出一点:相同级别的控件他们的约束在父控件去找
1、黄色的View与橘黄色View之间的关系,应该在ViewController中的View中

2、找到约束--将这条约束拿出来

3、设置约束中的属性

4、在touchBegin中设置:
self.spacingContraint.constant = 50;
修改完约束后,可以执行一个动画,让他看起来好看
[UIView animateWithDuration:2.0 animations:^{
self.spacingContraint.constant = 50;
}];
这种动画效果只能针对以前的的frame、bounds修改有效果。
而在修改Autolayout约束后,需要加一句代码
self.spacingContraint.constant = 50;
[UIView animateWithDuration:2.0 animations:^{
// 只需要在动画方法中:对修改约束的控件做一次布局就可以了
[self.orangeView layoutIfNeeded];
}];
约束动画总结:
** 在修改了约束之后,只要执行下面代码,就能做动画效果**
[UIViewanimateWithDuration:1.0animations:^{
[添加了约束的view layoutIfNeeded];
}];
3、SizeClass:(iPhone6-iPhone6p)实现屏幕多样化,界面大统一
1、仅仅是对屏幕进行了分类,排布UI元素还需要autolayout
(比如iPhone6的横竖屏状态就是一类,iPad横竖屏状态又是一类。)
2、不再有横竖屏概念,只有屏幕尺寸的概念
3、不再有具体尺寸的区别,只有抽象尺寸的概念
4、把宽度和高度分为三种情况
1.compact:(紧凑(小))

2.any:(任意)

3.regular:(宽松(大))

它其实和UIButton类比(在不同模式下,有不同的设置方式)
练习:设置一个UIButton在横屏下显示,在竖屏下不显示
1、首先设置屏幕状态,让后添加button

2、设置竖屏紧凑

3、运行,就可以啦
练习2、在横屏显示左上角,竖屏的时候显示到右下角
结合上一个练习,可以看到

这个时候点击灰色不可用的button控件

做完上面的,就会出现,选中,按钮就会出现,显示可用。

然后在不同的模式下,设置约束就可以做到显示不同屏幕下的不同约束

练习3、设置Unbutton在iPad情况下显示居中
1、先设置系统版本可以在任何模式下(iPad或iPhone下):

2、将控件--添加SizeClass模式下的显示,就可以做到任何屏幕的适配

3、然后添加—他在iPad中的情况。
目前SizeClass介绍中对iPad比较模糊,所以需要实际开发中根据需求来判断

运行,ok!
练习四、在任意情况下显示一张图片,在iPad中显示一张特殊的图片
1、设置好模式(宽松、紧凑、任意)下imageView的约束(autolayout)
初学者注意:不能通过这个修改在不同模式下的图片

2、选中图片中(会发现多了一些
*、-、+
)- :compact (紧凑)
+:regular (宽松)
那么就是剩下的就是
※:any(任意)

3、将需要在其他模式下显示的图片拖拽进去

4、然后当你切换的时候,就会根据不同的屏幕像是不同的图片了
关于:UILable在不同模式下的字体尺寸,在iPad中的尺寸变得大一些,等(不再累赘阐述)

网友评论