Programming/Mac & iOS

[iOS] addSubview & addChildViewController (P. S. Container View Controller)

MB Brad KWON 2017. 8. 22. 18:53

addSubview & addChildViewController


    addSubview는 view를 view hierarcky에 추가한다. addChildViewController는 Container View Controller에 child view controller를 추가한다. 전자의 경우, 하나의 view controller에서 event를 관리한다. 후자의 경우, 각각의 view controller들이 자신이 소유하고 있는 view의 event를 따로 관리하게 된다. 그리고 각 child view controller를 소유하고 있는 view controller를 container view controller라고 한다.


    우리가 가장 흔하게 볼 수 있는 container view controller의 예가 tab bar controller / navigation controller 등이 있다. 각 tab별로 view controller를 추가한다. 각 view controller는 해당 tab이 눌리면 화면 상에 추가되어 사용자 event를 각자 처리하게 된다. 이와는 별개로 사용자의 event를 받기만할 뿐, 따로 처리하는 로직을 분리하고 싶지 않으면 해당 view를 addSubview로 추가한다.




Container View Controller


    UIViewController를 상속한 클래스는 container view controller로 동작할 수 있다. container view controller는 자신이 소유하고 있는 child view controller의 내용물 (view, event 등)을 표현하는 로직을 관리한다. child view controller의 view는 contain view controller의 view와 연계되어 표시된다. 해당 container view controller는 child view controller들과 연계될 수 있도록 public interface로 선언해야 한다. container view controller의 interface들을 public으로 선언함으로써 child view controller들이 container view controller 구현부의 동작에 상관없이 각자의 역할을 수행한다.





    위 그림처럼 child view controller를 추가하면 된다. child view controller의 view가 view hierarcky에 추가되기 전에 container view controller에 추가해야한다. 이 과정이 선행되야 contain view controller는 자신이 관리하는 view와 child view controller에게 event를 전달할 수 있다. 마찬가지로 child view controller의 view가 제거된 후에는 child view controller에서 자기자신을 container view controller에서 제거해야 한다. 제거를 위한 메소드들은 child view controller가 아니라, container view controller에 의해서만 호출해야 Containment 동작에 예외 케이스를 줄일 수 있다.