Open churabou opened 6 years ago
class BaseView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
initializeView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initializeView() {}
}
extension BaseView {
func enableAutoLayout() {
translatesAutoresizingMaskIntoConstraints = false
}
}
class ViewController: UIViewController {
private var blue = BlueView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(blue)
}
}
class BlueView: BaseView {
private var orange = OrangeView()
private var red = RedView()
override func initializeView() {
backgroundColor = .blue
addSubview(orange)
orange.addSubview(red)
}
override func _layoutSubviews() {
snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(100)
}
orange.snp.makeConstraints { (make) in
make.top.left.equalToSuperview()
make.size.equalTo(40)
}
}
}
class RedView: BaseView {
override func initializeView() {
backgroundColor = .red
}
override func _layoutSubviews() {
snp.makeConstraints { (make) in
make.right.equalToSuperview()
make.centerY.equalToSuperview()
make.size.equalTo(20)
}
}
}
class OrangeView: BaseView {
override func initializeView() {
backgroundColor = .orange
}
}
class BaseView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
initializeView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initializeView() {}
override func layoutSubviews() {
super.layoutSubviews()
print("layoutSubviews: \(String(describing: type(of: self)) )")
_layoutSubviews()
}
func _layoutSubviews() { }
override func draw(_ rect: CGRect) {
print("draw: \(String(describing: type(of: self)) )")
}
}
extension BaseView {
func enableAutoLayout() {
translatesAutoresizingMaskIntoConstraints = false
}
}
layoutSubviews: BlueView
layoutSubviews: OrangeView
layoutSubviews: BlueView
layoutSubviews: OrangeView
layoutSubviews: RedView
layoutSubviews: OrangeView
layoutSubviews: RedView
layoutSubviews: RedView
draw: BlueView
draw: OrangeView
draw: RedView
LayoutSubViewsは複数回呼ばれる。
class BlueView: BaseView {
override func initializeView() {
backgroundColor = .blue
}
override func layoutSubviews() {
print("layout subviews")
print("before \(frame)")
snp.makeConstraints { (make) in
make.size.equalTo(60)
make.right.equalToSuperview()
make.centerY.equalToSuperview()
}
print("after \(frame)")
}
}
frameを決定する
制約の更新はupdateLayoutで行うのが良いらしい。
updateLayout -> layoutsubviews -> draw
子Viewから制約をつけていき、親Viewからレンダリングしていくらしい。
制約の更新を呼び出すには
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
layoutIfNeeded
(1 )
why