[Swift通天遁地]六、智能布局-(1)给视图添加尺寸和中心点的约束

本文将演示给视图添加尺寸和中心点的约束。

首先确保在项目中已经安装了所需的第三方库。

点击【Podfile】,查看安装配置文件。

1 source 'https://github.com/CocoaPods/Specs.git'
2 platform :ios, ‘12.03 use_frameworks!
4 
5 target 'DemoApp' do
6     pod 'SnapKit'
7 end

根据配置文件中的相关配置,安装第三方库。

然后点击打开【DemoApp.xcworkspace】项目文件。

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

 1 import UIKit
 2 //在当前的类文件中,引入已经安装的第三方类库
 3 import SnapKit
 4 
 5 class ViewController: UIViewController {
 6     
 7     //初始化一个视图对象,作为当前类的属性
 8     lazy var box = UIView()
 9     override func viewDidLoad() {
10         super.viewDidLoad()
11         // Do any additional setup after loading the view, typically from a nib.
12         
13         //将视图对象添加到根视图
14         self.view.addSubview(box)
15         //设置视图对象的背景颜色为橙色
16         box.backgroundColor = UIColor.orange
17         
18         //通过调用视图对象的创建约束的方法,
19         //给视图对象添加约束
20         box.snp.makeConstraints { (make) -> Void in
21             //首先给视图对象添加尺寸上的约束,
22             //在此约束视图对象的宽度和高度,
23             //它们的值始终保持为100
24             make.width.height.equalTo(100)
25             //约束视图对象的中心点的位置,
26             //该位置始终处于根视图的中心位置。
27             make.center.equalTo(self.view)
28         }
29     }
30     
31     override func didReceiveMemoryWarning() {
32         super.didReceiveMemoryWarning()
33         // Dispose of any resources that can be recreated.
34     }
35 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10266173.html