Reputation: 145
I have used in my UITableviewController
:
self.view.superview?.addSubview(PopUpControls)
It pops-up fine but not in the right position. How do you set the position for a subview?
Upvotes: 0
Views: 3210
Reputation: 11494
You probably just need to change the origin after you add the view as a sub-view:
// Set the Y (up, down) position of the view.
PopUpControls.frame.origin.y = <CGFLOAT>
// Set the X (left, right) position of the view
PopUpControls.frame.origin.x = <CGFLOAT>
To add constraints to a view, you do it like this:
// 1
if let superView = self.view.superview {
// 2
superView.addSubview(PopUpControls)
// 3
PopUpControls.translatesAutoresizingMaskIntoConstraints = false
// 4
NSLayoutConstraint.activate([
// 5
NSLayoutConstraint(item: PopUpControls, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1.0, constant: 15),
// 6
NSLayoutConstraint(item: PopUpControls, attribute: .left, relatedBy: .equal, toItem: superView, attribute: .left, multiplier: 1.0, constant: 5),
// 7
PopUpControls.heightAnchor.constraint(equalToConstant: 15),
//8
PopUpControls.widthAnchor.constraint(equalToConstant: 10)
])
}
Here is what I am doing:
This should be done in the viewDidLayoutSubviews
method of the controller.
Upvotes: 3
Reputation: 1620
self.view.superview?.addSubview
Something has gone wrong if you ever need to do this.
The common way to send messages back up the chain is to use delegation.
Basically you define a protocol that one object has a reference to and the other object implements. That way you can send messages from the first object to the second. A child view should never be directly responsible for adding views directly to it's superview.
For the actual problem you have with setting the position, it depends on if you are using autolayout or not. If you are not them you simply need to set the x and y components of the view PopUpControls frame. If you are using autolayout then you will need to define it's constraints.
Upvotes: 0