swift3.0纯代码实现屏幕自适应
笔者有个习惯,就是能用代码实现的功能,绝对不用故事板。包括任何按钮的创建,视图的处理,都走纯代码路线。正是如此,在笔者首款应用开发过程中,就屏幕自适应这个问题,走了很多弯路。后来笔者在百度的过程中,结合自己的方法,总结出一套万能代码自适应屏幕的方法。
首先,定义两个全局变量
然后在类视图控制器的viewDidLoad()中为这两个变量赋值
1
2 var screenWidth = CGFloat(nan: 0,signaling: false)
var screenHeight = CGFloat(nan: 0,signaling: false)
1
2 screenWidth = self.view.frame.width //the main screen size of width
screenHeight = self.view.frame.height //the main screen size of height
之后你需要选择一个固定的屏幕点阵宽高作为模版,在这里我选的是7Plus宽是414,高是736(注意:这里非像素值大小) 然后你就可以按照这个机型来适配屏幕,在模拟器中观测屏幕上各个视图区块的位置和大小,然后按需为frame创建CGRect
1
2
3
4
5
6
7
8
9 func Btn(_x:Int,_y:Int,_width:Int,_height:Int,_str:String,_pic:String)->UIButton
{
let btn=UIButton()
btn.setImage(UIImage(named: _pic), for: [])
btn.setTitle(_str, for: [])
btn.titleLabel?.font=UIFont.systemFont(ofSize: 15*screenWidth/414)
btn.frame=CGRect(x:_x*Int(screenWidth)/414,y:_y*Int(screenHeight)/736,width:_width*Int(screenWidth)/414,height:_height*Int(screenWidth)/414)
return btn
}
在Btn函数的引用中,以7PLUS为模版,为各个参数填写相应的参数 其他视图如图片等如法炮制。
嗨、骚年、快来消灭0回复。