前言:
1、在Mac OS中NSWindow的父類是NSResponder,而在iOS中UIWindow的父類是UIView。程序一般只有一個(gè)窗口但是會(huì)又很多視圖。
2、UIView的作用:描畫和動(dòng)畫,視圖負(fù)責(zé)對其所屬的矩形區(qū)域描畫、布局和子視圖管理、事件處理、可以接收觸摸事件、事件信息的載體等等。
我在前面詳細(xì)介紹了setNeedsDisplay , setNeedsLayout和layoutIfNeeded 詳情請點(diǎn)擊。
下面介紹的是view添加以及刪除時(shí)所觸發(fā)的方法
// 當(dāng)視圖添加子視圖時(shí)調(diào)用
- (void)didAddSubview:(UIView *)subview;
// 當(dāng)子視圖從本視圖移除時(shí)調(diào)用
- (void)willRemoveSubview:(UIView *)subview;
// 當(dāng)視圖即將加入父視圖時(shí) / 當(dāng)視圖即將從父視圖移除時(shí)調(diào)用
- (void)willMoveToSuperview:(nullable UIView *)newSuperview;
// 當(dāng)試圖加入父視圖時(shí) / 當(dāng)視圖從父視圖移除時(shí)調(diào)用
- (void)didMoveToSuperview;
// 當(dāng)視圖即將加入父視圖時(shí) / 當(dāng)視圖即將從父視圖移除時(shí)調(diào)用
- (void)willMoveToWindow:(nullable UIWindow *)newWindow;
// 當(dāng)視圖加入父視圖時(shí) / 當(dāng)視圖從父視圖移除時(shí)調(diào)用
- (void)didMoveToWindow;
上面是資料說的,究竟對不對呢?我們用swift版的代碼來驗(yàn)證下。
先自定義一個(gè)<code>TestView</code>類
TestView代碼如下:
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 當(dāng)試圖加入父視圖時(shí) / 當(dāng)視圖從父視圖移除時(shí)調(diào)用
override func didMoveToSuperview() {
print("\(#function)")
}
// 當(dāng)視圖即將加入父視圖時(shí) / 當(dāng)視圖即將從父視圖移除時(shí)調(diào)用
override func willMove(toSuperview newSuperview: UIView?) {
print("\(#function)")
}
override func didAddSubview(_ subview: UIView) {
print("3秒后\(#function)")
}
override func willRemoveSubview(_ subview: UIView) {
print("6秒后\(#function)")
}
然后將該TestView創(chuàng)建實(shí)例,添加到控制器的view,設(shè)背景色為紫色,并將001賦給tag值
override func viewDidLoad() {
super.viewDidLoad()
let testV = TestView()
testV.frame = self.view.bounds
testV.backgroundColor = UIColor.purple
testV.tag = 001
self.view.addSubview(testV)
上面方法觸發(fā)了
willMove(toSuperview:)
和didMoveToSuperview()
,驗(yàn)證了當(dāng)視圖即將加入父視圖時(shí)和當(dāng)試圖加入父視圖時(shí)調(diào)用
之后在viewDidLoad
添加一個(gè)帶有延遲的添加紅色view代碼,值得一提的是,這是最新swift3.1的GCD延時(shí)方法
//如果不需要在主線程執(zhí)行,就去掉main
DispatchQueue.main.asyncAfter(deadline: .now()+3.0) {
let view = UIView.init(frame: CGRect(x: 10, y: 100, width: 100, height: 60))
view.backgroundColor = UIColor.red
testV.addSubview(view)
}
上面方法觸發(fā)了didAddSubview
,驗(yàn)證了當(dāng)視圖添加子視圖時(shí)會(huì)調(diào)用
DispatchQueue.main.asyncAfter(deadline: .now()+6.0, execute: {
let tagView: TestView = self.view .viewWithTag(001) as! TestView
tagView.removeFromSuperview()
})
上面方法觸發(fā)了willRemoveSubview
,驗(yàn)證了當(dāng)子視圖從本視圖移除時(shí)會(huì)被調(diào)用,同時(shí),willMove(toSuperview:)
和didMoveToSuperview()
也被調(diào)用了,分別驗(yàn)證了當(dāng)視圖即將從父視圖移除時(shí) 和 當(dāng)視圖從父視圖移除時(shí)會(huì)被調(diào)用
經(jīng)證實(shí),資料所述屬實(shí)。
人家發(fā)現(xiàn)的即便是對,但終歸是人家的,只有自己驗(yàn)證才是屬于自己的。