Skip to content
Khoa Pham@onmyway133

How to fight loadView in iOS

1 min read

Everything works fine until I need custom root UIView to handle hit testing.

class ThroughView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        guard let slideView = subviews.first else {
            return false
        }

        return slideView.hitTest(convert(point, to: slideView), with: event) != nil
    }
}
class PanViewController: UIViewController {
    override func loadView() {
        view = ThroughView()
    }
}

But I get UIView-Encapsulated-Layout-Height and UIView-Encapsulated-Layout-Width 0 for the root view 😠

I suspect default root view has auto resizing masks by default. I tried below but it does not work

class PanViewController: UIViewController {
    override func loadView() {
        view = ThroughView()
		view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }
}

A quick fix is to apply Auto Layout

override func loadView() {
    view = ThroughView()
    view.translatesAutoresizingMaskIntoConstraints = false
}

class ThroughView: UIView {
    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        guard let superview = superview else {
            return
        }

        NSLayoutConstraint.on([pinEdges(view: superview)])
    }
}

Keep reading

Type to search titles and full text.

↑ ↓ move↵ openPagefind