I am adding a subview to a view and I want it to fill the height and width of the view. I am having difficulty with constraints. Any help is appreciated. This is what I have currently:
self.view.addSubview(self.mainView)
var leftSideConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
var bottomConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
var widthConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0)
var heightConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([leftSideConstraint, bottomConstraint, widthConstraint, heightConstraint])
Swift 5
Here is an elegant way with using UIView extension
extension UIView {
func addConstrained(subview: UIView) {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.topAnchor.constraint(equalTo: topAnchor).isActive = true
subview.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
subview.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
subview.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
And then you add a subview wherever you need it with
yourContainerView.addConstrained(subview: yourSubview)
The following code should work:
let mainView = UIView() //Make sure your mainView is initialized
mainView.backgroundColor = UIColor.blueColor() //For test purpose
mainView.setTranslatesAutoresizingMaskIntoConstraints(false) //Don't forget this line
view.addSubview(mainView)
var leftSideConstraint = NSLayoutConstraint(item: mainView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0)
var bottomConstraint = NSLayoutConstraint(item: mainView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
var widthConstraint = NSLayoutConstraint(item: mainView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1.0, constant: 0.0)
var heightConstraint = NSLayoutConstraint(item: mainView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: 0.0)
view.addConstraints([leftSideConstraint, bottomConstraint, heightConstraint, widthConstraint])
As an alternative, you can use the Auto layout Visual Format Language:
let mainView = UIView() //Make sure your mainView is initialized
mainView.backgroundColor = UIColor.blueColor() //For test purpose
mainView.setTranslatesAutoresizingMaskIntoConstraints(false) //Don't forget this line
view.addSubview(mainView)
var viewsDict = ["mainView" : mainView]
var horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[mainView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)
var verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[mainView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)
view.addConstraints(horizontalConstraints)
view.addConstraints(verticalConstraints)
Related
I'm trying to reproduce a scenario like this where the red and blue rectangles can occupy same width and height (and same gap between them) for different screen sizes.
I'm using NSLayoutConstraint (I know that anchors are preferred now, just trying to explore the basics). I tried the following code in swift playground:
import Foundation
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var firstColorView: UIView!
var secondColorView: UIView!
override func viewWillAppear(_ animated: Bool) {
var myView: UIView!
myView = view
myView.backgroundColor = .white
firstColorView = UIView()
secondColorView = UIView()
firstColorView.backgroundColor = .red
secondColorView.backgroundColor = .blue
myView.addSubview(firstColorView)
myView.addSubview(secondColorView)
//myView.translatesAutoresizingMaskIntoConstraints = false
//view.addSubview(myView)
// horizontal constraints
let left_constraint = NSLayoutConstraint(item: firstColorView, attribute: .leftMargin, relatedBy: .equal, toItem: myView, attribute: .left, multiplier: 1.0, constant: 20)
let middle_constraint = NSLayoutConstraint(item: secondColorView, attribute: .leftMargin, relatedBy: .equal, toItem: firstColorView, attribute: .right, multiplier: 1.0, constant: 10)
let right_constraint = NSLayoutConstraint(item: myView, attribute: .rightMargin, relatedBy: .equal, toItem: secondColorView, attribute: .right, multiplier: 1.0, constant: 20)
let width_constraint = NSLayoutConstraint(item: firstColorView, attribute: .width, relatedBy: .equal, toItem: secondColorView, attribute: .width, multiplier: 1.0, constant: 0)
// vertical constraints
let top_constraint1 = NSLayoutConstraint(item: firstColorView, attribute: .top, relatedBy: .equal, toItem: myView, attribute: .top, multiplier: 1.0, constant: 10)
let top_constraint2 = NSLayoutConstraint(item: secondColorView, attribute: .top, relatedBy: .equal, toItem: myView, attribute: .top, multiplier: 1.0, constant: 10)
let bottom_constraint1 = NSLayoutConstraint(item: myView, attribute: .bottom, relatedBy: .equal, toItem: firstColorView, attribute: .bottom, multiplier: 1.0, constant: 10)
let bottom_constraint2 = NSLayoutConstraint(item: myView, attribute: .bottom, relatedBy: .equal, toItem: secondColorView, attribute: .bottom, multiplier: 1.0, constant: 0)
NSLayoutConstraint.activate([left_constraint, middle_constraint, right_constraint, width_constraint, top_constraint1, top_constraint2, bottom_constraint1, bottom_constraint2])
self.view.layoutIfNeeded()
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = MyViewController()
But all it shows is a white screen, whose width doesn't match an iphone's. What am I doing wrong here? Why can't I see the red and blue screen?
You miss
firstColorView.translatesAutoresizingMaskIntoConstraints = false
secondColorView.translatesAutoresizingMaskIntoConstraints = false
I am unable to understand where to add subview so that the button can lie in middle of the existing views.
This is work for me. (swift 4.0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let yourView = self.view
addButtonOnCentral(yourView!)
}
func addButtonOnCentral(_ view:UIView) {
let btn = UIButton.init()
btn.backgroundColor = UIColor.yellow
btn.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(btn)
let widthConstraint = NSLayoutConstraint(item: btn, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20)
let heightConstraint = NSLayoutConstraint(item: btn, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30)
let xConstraint = NSLayoutConstraint(item: btn, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: btn, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])
}
I have a testView UIView and subview named testViewSub. The testView is constrained by using NSLayoutConstraint. And i set subView frame to testView.bounds. But it doesn't work. Here is the code
let testView = UIView()
testView.backgroundColor = UIColor.red
self.view.addSubview(testView)
testView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: testView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 30).isActive = true
NSLayoutConstraint(item: testView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: -30).isActive = true
NSLayoutConstraint(item: testView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 200).isActive = true
NSLayoutConstraint(item: testView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.15, constant: 0).isActive = true
let testViewSub = UIView()
testViewSub.backgroundColor = UIColor.green
testViewSub.frame = testView.bounds
self.testView.addSubview(testViewSub)
testViewSub.translatesAutoresizingMaskIntoConstraints = false
But if i set testView's frame using CGRect. It works.
Where is the layout happening? I've run into issues before where the constraints don't take effect until the view appears, so relying on frames to be the correct size in viewDidLoad or viewWillAppear causes problems.
In this case, adding testViewSub in viewDidAppear worked for me, though I'm not sure it's the way I would recommend. Using constraints to lay it out, just as with testView, will also work from viewDidLoad or viewWillAppear:
// layout constraints however you want - in this case they are such that green view's frame = red view's bounds
let testViewSub = UIView()
testViewSub.backgroundColor = UIColor.green
self.testView.addSubview(testViewSub)
NSLayoutConstraint(item: testViewSub, attribute: .leading, relatedBy: .equal, toItem: testView, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: testViewSub, attribute: .trailing, relatedBy: .equal, toItem: testView, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: testViewSub, attribute: .top, relatedBy: .equal, toItem: testView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: testViewSub, attribute: .height, relatedBy: .equal, toItem: testView, attribute: .height, multiplier: 1.0, constant: 0).isActive = true
testViewSub.translatesAutoresizingMaskIntoConstraints = false
This will also deal with rotation better than simply setting the frame.
i'm trying to center a view in the parent view but its not centering as expected. Here is my code an a screenshot of the result.
emptyView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emptyView)
let centerXConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
self.view.addConstraints([centerXConstraint])
self.view.addConstraints([centerYConstraint])
Here is the code,
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var emptyView: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
self.emptyView.translatesAutoresizingMaskIntoConstraints = false
let centerXConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
let widthConstraint = NSLayoutConstraint(item: emptyView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
let heightConstraint = NSLayoutConstraint(item: emptyView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
self.view.addConstraints([centerXConstraint, centerYConstraint, widthConstraint, heightConstraint])
self.view.layoutIfNeeded()
}
}
If you are using label or button or any other view that have intrinsic size, there is no need for height and width constraints
ViewController Interface :
Output :
Try this code
emptyView.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: emptyView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: emptyView.frame.size.width)
let heightConstraint = NSLayoutConstraint(item: emptyView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: emptyView.frame.size.height)
var constraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.alignAllCenterX,
metrics: nil,
views: ["superview":view, "label": emptyView])
view.addConstraints(constraints)
// Center vertically
constraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.alignAllCenterY,
metrics: nil,
views: ["superview":view, "label": emptyView])
view.addConstraints(constraints)
view.addConstraints([ widthConstraint, heightConstraint])
func setupView()
{
self.blueView = UIView()
self.blueView?.backgroundColor = UIColor.blueColor()
self.blueView?.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.blueView!)
let blueViewCenterXConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 0.6, constant: 0)
let blueViewCenterYConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
let blueViewWidthConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0.6, constant: 150)
let blueViewHeightConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 150)
self.addConstraints([blueViewCenterXConstraint,blueViewCenterYConstraint,blueViewWidthConstraint,blueViewHeightConstraint])
self.redView = UIView()
self.redView?.backgroundColor = UIColor.redColor()
self.redView?.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.redView!)
let redViewCenterXConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.TrailingMargin , multiplier: 0.5, constant: 0)
let redViewCenterYConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Top, multiplier: 0.5, constant: 0)
let redViewWidthConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Width, multiplier: 0.5, constant: 150)
let redViewHeightConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Height, multiplier: 0.5, constant: 150)
self.addConstraints([redViewCenterXConstraint,redViewCenterYConstraint,redViewWidthConstraint,redViewHeightConstraint])
}
I have applied above code for Creating and Setting Auto Layout Constraint for UITextView for Universal App. I want to Put these both UITextView beside Each other for Every Device with the space of 10 between them horizontally and centered in Vertically. Will Anybody please be Grateful to fix mentioned issue, which would be helpful a lot to me.
I've taken the liberty of looking at you previous question and furthermore I've used NSLayoutAnchors (described here) because I think they are easier to read.
Based on the above, this UIView subclass:
import UIKit
class UIViewUsingTextField: UIView {
let width: CGFloat = 150.0
var blueview = UIView()
var redview = UIView()
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.whiteColor()
self.setupView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
func setupView() {
//add blue view
blueview.backgroundColor = UIColor.blueColor()
blueview.translatesAutoresizingMaskIntoConstraints = false
addSubview(blueview)
//center the blue view and move it 1/2 view width to the left
blueview.centerXAnchor.constraintEqualToAnchor(self.centerXAnchor, constant: -(width/2)).active = true
blueview.centerYAnchor.constraintEqualToAnchor(self.centerYAnchor).active = true
blueview.widthAnchor.constraintEqualToConstant(width).active = true
blueview.heightAnchor.constraintEqualToConstant(width).active = true
//add red view
redview.backgroundColor = UIColor.redColor()
redview.translatesAutoresizingMaskIntoConstraints = false
addSubview(redview)
//place red view 10 px to the right of blue view
redview.leadingAnchor.constraintEqualToAnchor(blueview.trailingAnchor, constant: 10.0).active = true
redview.centerYAnchor.constraintEqualToAnchor(blueview.centerYAnchor).active = true
redview.widthAnchor.constraintEqualToAnchor(blueview.widthAnchor).active = true
redview.heightAnchor.constraintEqualToAnchor(blueview.heightAnchor).active = true
}
}
Gives me this layout
Hope this resembles what you were after.
I have included a solution using your code, but would also like to show you how it is done using constraintWithVisualFormat, because I think it reads easier.
Solution for you code:
Note that the width are set to a fixed value here. Not sure if this is really what you want.
func setupView()
{
self.blueView = UIView()
self.blueView?.backgroundColor = UIColor.blueColor()
self.blueView?.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.blueView!)
let blueViewCenterXConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -5)
let blueViewCenterYConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
let blueViewWidthConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 150)
let blueViewHeightConstraint = NSLayoutConstraint(item: self.blueView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 150)
self.view.addConstraints([blueViewCenterXConstraint,blueViewCenterYConstraint,blueViewWidthConstraint,blueViewHeightConstraint])
self.redView = UIView()
self.redView?.backgroundColor = UIColor.redColor()
self.redView?.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.redView!)
let redViewCenterXConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Trailing , multiplier: 1, constant: 10)
let redViewCenterYConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let redViewWidthConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 1)
let redViewHeightConstraint = NSLayoutConstraint(item: self.redView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: blueView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 1)
self.view.addConstraints([redViewCenterXConstraint,redViewCenterYConstraint,redViewWidthConstraint,redViewHeightConstraint])
}
Solution using visual constraints
let views = ["redView": redView!, "blueView": blueView!]
//setup the horizontal constraints to have 15 leading and trailing constraints, equal widths for blueView and redView and 10 spacing in between.
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[blueView(==redView)]-10-[redView]-15-|", options: .AlignAllCenterY, metrics: nil, views: views))
//set the height of the two views
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[blueView(150)]", options: .AlignAllCenterX, metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[redView(150)]", options: .AlignAllCenterX, metrics: nil, views: views))
//align the two views relative to the centre of the superview.
blueView!.centerYAnchor.constraintEqualToAnchor(view!.centerYAnchor, constant: 0).active = true
redView!.centerYAnchor.constraintEqualToAnchor(blueView!.centerYAnchor).active = true
Replace self.view with self for your example