- 自定义视图
- 使用NSLayoutConstraint实现布局
- Block的使用,并防止循环引用
- 使用deinit代替OC中的delloc
class MyNavigationBar: UIView {
typealias BackBlock = ()->Void
var backBlock: BackBlock?
var backButton = UIButton()
var titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
backgroundColor = UIColor(colorHex: 0xEEEEEE)
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 88)
self.addSubview(backButton)
backButton.translatesAutoresizingMaskIntoConstraints = false
backButton.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
backButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
backButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
self.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
titleLabel.heightAnchor.constraint(equalToConstant: 44).isActive = true
backButton.setImage(UIImage(named: "navi_back_black"), for: .normal)
backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
titleLabel.text = ""
titleLabel.textColor = UIColor(colorHex: 0x333333)
titleLabel.font = UIFont.boldSystemFont(ofSize: 18)
titleLabel.textAlignment = .center
}
@objc func backAction() {
self.backBlock?()
}
}
class BaseViewController: UIViewController {
var myNaviBar = MyNavigationBar()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationController?.navigationBar.isHidden = true
view.addSubview(myNaviBar)
if navigationController?.viewControllers.count ?? 0 > 1 {
weak var weakself = self
myNaviBar.backBlock = {
weakself?.navigationController?.popViewController(animated: true)
}
}
else {
myNaviBar.backButton.isHidden = true
}
}
deinit {
print("deinit - \(Self.self)")
}
}