iOS10 UI教程層次結構的事件,層次結構中存在7個事件,對於這些事件的介紹如表1-3所示。經過這些事件,能夠監聽視圖,當視圖在層次結構上發生變化時能夠被攔截,也能夠經過父視圖或子視圖進行管理。swift
表1-3 層次結構的事件ide
事件ui |
功能this |
didAddSubview(_:) spa |
當加入視圖完成後調用.net |
willRemoveSubview(_:) code |
在刪除視圖以前調用blog |
willMove(toSuperview:) 教程 |
當移動視圖以前調用事件 |
didMoveToSuperview() |
當視圖移動完成後調用 |
willMove(toWindow:) |
當視圖移動到WINDOW以前調用 |
didMoveToWindow() |
當視圖移動到WINDOW後調用 |
【示例1-9:HierarchyEvents】如下將使用層次結構的事件實現視圖的監聽。具體的操做步驟以下:
(1)建立一個基於UIView的類文件,命名爲CustomView。
(2)打開CustomView.swift文件,編寫代碼,經過層次結構的事件監聽視圖。代碼以下:
import UIKit class CustomView: UIView { //當視圖移動完成後調用 override func didMoveToSuperview() { print("I have a superview!") } //當加入視圖完成後調用 override func didAddSubview(_ subview: UIView) { print("The subView \(subview) has been added") } //當視圖移動到WINDOW後調用 override func didMoveToWindow() { print("I've been attached to this window hierarchy:\(window!)") } }
(3)打開Main.storyboard文件,選擇主視圖,在Show the Identity inspector面板中找到Class,將其設置爲剛纔建立的類即CustomView。此時運行程序,會在應用程序輸出窗口輸出如下內容:
The subView <_UILayoutGuide: 0x7fbd57a00c40; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x600000028fe0>> has been added The subView <_UILayoutGuide: 0x7fbd57a07990; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x600000029000>> has been added I've been attached to this window hierarchy:<UIWindow: 0x7fbd55c05f70; frame = (0 0; 375 667); gestureRecognizers = <NSArray: 0x618000054430>; layer = <UIWindowLayer: 0x618000029dc0>> I have a superview!
iOS10 UI教程層次結構的事件
相關閱讀:iOS10 UI教程視圖和子視圖的可見性