Questioner
Questioner

Reputation: 2541

Programmatically adding constraints in Swift does not work

I added the following code to center a programmatically added view:

let horizontalConstraint = NSLayoutConstraint(item: newView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)

It doesn't work. The view is not centered. It is on the left still.

EDIT:

    override func viewDidLoad() {
    super.viewDidLoad()

    newView = LineChartView(frame: CGRectMake(0, 0, 50, 50))
    newView?.delegate = self
    newView?.drawBordersEnabled = true
    newView?.noDataText = "No Data"
    newView?.noDataTextDescription = "No Data"
    newView?.borderColor = UIColor.blackColor()

    self.view.addSubview(newView!)

Upvotes: 0

Views: 2906

Answers (1)

Wez
Wez

Reputation: 10712

You need to pick a side my friend, If you are using auto layout, don't initialise your objects with a frame. Try something like this...

var newView:LineChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    newView = LineChartView()
    newView.translatesAutoresizingMaskIntoConstraints = false
    newView.delegate = self
    newView.drawBordersEnabled = true
    newView.noDataText = "No Data"
    newView.noDataTextDescription = "No Data"
    newView.borderColor = UIColor.blackColor()
    self.view.addSubview(newView)

    let width = NSLayoutConstraint(item: newView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50)
    let height = NSLayoutConstraint(item: newView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50)
    newView.addConstraint(width)
    newView.addConstraint(height)
    let x = NSLayoutConstraint(item: newView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)
    let y = NSLayoutConstraint(item: newView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
    self.view.addConstraint(x)
    self.view.addConstraint(y)

}

If your LineChartView object is a subclass of UIView then this should work, and you should have a 50x50 object in the middle of your superview.

If you are going to be doing constraints like this in code you should consider using Apples Visual Formatting Language.

Upvotes: 1

Related Questions