在过去只有iphone4的时候,可以在代码里将一个可视单元的位置写死,这样是没问题的,但随着iPhone5,6的发布,屏幕尺寸有了越来越多种可能。这就要求App的UI控件具有在不同屏幕尺寸的设备上具有一定动态的可调性,实现较好的UI展示效果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //创建组件 var textField = UITextField (frame: CGRectZero ) //这里不再需要刻意制定x,y坐标 textField.borderStyle = UITextBorderStyle . RoundedRect self .view.addSubview(textField) var button = UIButton .buttonWithType( UIButtonType . System ) as UIButton ; button.setTitle( "按钮" , forState: UIControlState . Normal ) button.backgroundColor = UIColor (red: 55/255, green: 186/255, blue: 89/255, alpha: 0.5) self .view.addSubview(button) var textView = UITextView (frame: CGRectZero ) textView.text= "hangge.com" textView.backgroundColor = UIColor (red: 55/255, green: 186/255, blue: 89/255, alpha: 0.5) self .view.addSubview(textView) //使用Auto Layout的方式来布局 textField.setTranslatesAutoresizingMaskIntoConstraints( false ) button.setTranslatesAutoresizingMaskIntoConstraints( false ) textView.setTranslatesAutoresizingMaskIntoConstraints( false ) //创建一个控件数组 var views: NSMutableDictionary = NSMutableDictionary () views.setValue(textField, forKey: "textField" ) views.setValue(button, forKey: "button" ) views.setValue(textView, forKey: "textView" ) //创建一个水平居中约束(按钮) var constraint: NSLayoutConstraint = NSLayoutConstraint (item: button, attribute: . CenterX , relatedBy: . Equal , toItem: self .view, attribute: . CenterX , multiplier: 1.0, constant: 0.0) self .view.addConstraint(constraint) //创建水平方向约束 self .view.addConstraints( NSLayoutConstraint .constraintsWithVisualFormat( "H:|-5-[textField]-5-|" , options: nil , metrics: nil , views: views)) self .view.addConstraints( NSLayoutConstraint .constraintsWithVisualFormat( "H:|-5-[textView]-5-|" , options: nil , metrics: nil , views: views)) //创建垂直方向约束 self .view.addConstraints( NSLayoutConstraint .constraintsWithVisualFormat( "V:|-20-[textField]-20-[textView]-20-[button]-20-|" , options: nil , metrics: nil , views: views)) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } } |
二,Size Classes(适配各类型的屏幕)
Swift - 使用Auto Layout和Size Classes实现页面自适应弹性布局
原文:http://www.cnblogs.com/Free-Thinker/p/4841144.html