
getTopLevel 메서드는 UIView 계층구조에서 최상위 뷰를 반환하도록 설계되었습니다. 그러나 CustomView의 서브뷰인 AnotherView를 포함하고 있는 경우 nil을 반환하는 이유는 다음과 같습니다.
- getTopLevel 메서드는 UIView의 서브클래스에서 호출할 수 없습니다. CustomView의 서브뷰인 AnotherView는 UIView의 서브클래스이기 때문에 getTopLevel 메서드를 호출할 수 없습니다.
올바르게 호출해야 하는 방법은 다음과 같습니다.
- getTopLevel 메서드를 CustomView의 상위 뷰에서 호출해야 합니다. 예를 들어, CustomView의 상위 뷰인 ViewController에서 getTopLevel 메서드를 호출할 수 있습니다.
#hostingforum.kr
swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let customView = CustomView()
view.addSubview(customView)
let topLevelView = customView.getTopLevel()
print(topLevelView) // nil
}
}
- getTopLevel 메서드를 CustomView의 상위 뷰인 ViewController에서 호출할 수 있습니다.
#hostingforum.kr
swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let customView = CustomView()
view.addSubview(customView)
let topLevelView = view.getTopLevel()
print(topLevelView) // ViewController
}
}
- getTopLevel 메서드를 사용하지 않고, CustomView의 서브뷰인 AnotherView를 직접 참조할 수 있습니다.
#hostingforum.kr
swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let customView = CustomView()
view.addSubview(customView)
let anotherView = customView.subviews.first as? AnotherView
print(anotherView) // AnotherView
}
}
2025-04-19 10:44