Swift学习08(swift常用)
2018-05-21 本文已影响7人
coderhlt
一、自定义view
import UIKit
class TestView: UIView {
var view:UIView?
//1.重写init方法
override init(frame: CGRect) {
super.init(frame:frame)
view=UIView()
self.addSubview(view!)
view?.backgroundColor=UIColor.red
}
//加载xib,storyboard文件的初始化,即使纯代码swift也要求实现此方法要不然会报错
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//2.重写layoutSubviews布局子控件
override func layoutSubviews() {
super.layoutSubviews()
view?.frame=CGRect(x: 0, y: 0, width: 40, height: 40);
}
}
二、 SnapKit的基本使用
SnapKit是大名鼎鼎的Masonry的Swift版本,作者@Robert Payne和Masonry是同一个人。是一套轻量级的布局框架,同样适用链式语法封装Apple的自动布局约束。其用法基本和Masonry差不多
import UIKit
import SnapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let redview = UIView()
self.view.addSubview(redview)
redview.backgroundColor=UIColor.red
//添加约束
redview.snp.makeConstraints { (make) in
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(100)
make.left.equalTo(self.view.snp.left).offset(10)
make.right.equalTo(self.view).offset(-100)
make.height.equalTo(110)
}
let greenview = UIView()
self.view.addSubview(greenview)
greenview.backgroundColor=UIColor.green
greenview.snp.makeConstraints { (make) in
make.bottom.equalToSuperview().offset(-100)
make.left.equalToSuperview().offset(100)
make.right.equalToSuperview().offset(-100)
make.height.equalTo(60)
}
let yelloweview = UIView()
self.view.addSubview(yelloweview)
yelloweview.backgroundColor=UIColor.yellow
yelloweview.snp.makeConstraints { (make) in
make.top.equalTo(greenview.snp.bottom).offset(10)
make.left.equalToSuperview().offset(100)
make.right.equalToSuperview().offset(-100)
make.height.equalTo(60)
}
let lable = UILabel()
lable.text="测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试";
lable.numberOfLines=0
lable.backgroundColor=UIColor.yellow
self.view.addSubview(lable)
lable.snp.makeConstraints { (make) in
make.top.equalTo(redview.snp.bottom).offset(10);
make.leading.equalToSuperview().offset(10)
make.width.lessThanOrEqualTo(60)
}
let btn = UIButton()
btn.backgroundColor=UIColor.red
self.view.addSubview(btn)
btn.snp.makeConstraints { (make) in
make.left.equalTo(lable.snp.right).offset(10)
make.top.equalTo(redview.snp.bottom).offset(10)
make.size.equalTo(CGSize(width: 100, height: 100))
}
//重置约束
redview.snp.remakeConstraints { (make) in
make.left.top.equalToSuperview().offset(10)
make.width.height.equalTo(200)
}
//更新约束
yelloweview.snp.updateConstraints { (make) in
make.right.equalTo(self.view.snp.right).offset(-10)
}
}
}