I am testing pan Gesture Recognizer. I add a white Container to view and then add another red container to the white container.
When I am printing the whiteContainer.frame.orgin I get correct CGPoint numbers but when I print redContaner CGPoint numbers I get 0.0, 0.0
class ViewController6 : UIViewController {
let whiteContainer = UIView()
let redContainer = UIView()
var pointOrigin2: CGPoint?
var pointOrigin3: CGPoint?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func viewDidLayoutSubviews() {
pointOrigin2 = whiteContainer.frame.origin
print(pointOrigin2!)
pointOrigin3 = redContainer.frame.origin
print(pointOrigin3!)
}
private func setupView() {
view.backgroundColor = .black
configureContainer()
configureRedContainer()
addPanGestureRecognizare()
}
func configureContainer() {
view.addSubview(whiteContainer)
whiteContainer.translatesAutoresizingMaskIntoConstraints = false
whiteContainer.backgroundColor = .white
NSLayoutConstraint.activate([
whiteContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
whiteContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor),
whiteContainer.widthAnchor.constraint(equalToConstant: 200),
whiteContainer.heightAnchor.constraint(equalToConstant: 200)
])
}
func configureRedContainer() {
whiteContainer.addSubview(redContainer)
redContainer.translatesAutoresizingMaskIntoConstraints = false
redContainer.backgroundColor = .red
NSLayoutConstraint.activate([
redContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
redContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor),
redContainer.widthAnchor.constraint(equalToConstant: 50),
redContainer.heightAnchor.constraint(equalToConstant: 50)
])
}
When I am adding red Container to view (not whiteContainer.addSubview(red Container) ) I get the correct CGPoint number of the white and red container.
Why ?
Viewcontroller hasn't any calculation for the frames for subviews is not in own view if you add in viewDidLoad
. If you add a subview to ViewController's view , then yes ViewController makes calculation for that view but if you add subview to view's subview , it doesnt. Thats why you can see the whiteContainer
frame is not zero and redContainer
is zero.
To make this you should say 'view , you should calculation it'. Thats why you must use view.layoutIfNeeded()
after the constraints settings .
This gonna fix your problem
func configureRedContainer() {
whiteContainer.addSubview(redContainer)
redContainer.translatesAutoresizingMaskIntoConstraints = false
redContainer.backgroundColor = .red
NSLayoutConstraint.activate([
redContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
redContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor),
redContainer.widthAnchor.constraint(equalToConstant: 50),
redContainer.heightAnchor.constraint(equalToConstant: 50)
])
view.layoutIfNeeded() // must add after setting constraints
}