Rehaan Advani
Rehaan Advani

Reputation: 975

How do I add constraints programmatically to UISegmentedControl

Here is my code for a UISegmentedControl:

   employeeSegmentedControl = UISegmentedControl(items: items)
    employeeSegmentedControl.selectedSegmentIndex = 0
    employeeSegmentedControl.backgroundColor = UIColor(red: 41/255, green: 128/255, blue: 185/255, alpha: 1.0)
    employeeSegmentedControl.tintColor = UIColor.whiteColor()
    employeeSegmentedControl.addTarget(self, action: Selector("indexChanged:"), forControlEvents: .ValueChanged)
    self.view.addSubview(employeeSegmentedControl)

    employeeSegmentedControl.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addConstraint(NSLayoutConstraint(item: employeeSegmentedControl, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0))
    self.view.addConstraint(NSLayoutConstraint(item: employeeSegmentedControl, attribute: .Height, relatedBy: .Equal, toItem: self.searchController.searchBar, attribute: .Height, multiplier: 1.0, constant: 0.0))
    self.view.addConstraint(NSLayoutConstraint(item: employeeSegmentedControl, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
    self.view.addConstraint(NSLayoutConstraint(item: employeeSegmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: self.searchController.searchBar, attribute: .CenterY, multiplier: 1.2, constant: 0.0))

As you can see, I am adding constraints to the UISegmentedControl, but my app crashes. Here is my error message:

2015-09-03 18:50:52.241 Employee Keeper[14424:11105086] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: A multiplier of 0 or a nil second item together with a location for the first attribute creates an illegal constraint of a location equal to a constant. Location attributes must be specified in pairs' *** First throw call stack:

What am I doing wrong?

Upvotes: 3

Views: 7734

Answers (1)

ZYiOS
ZYiOS

Reputation: 5280

I think it's because your self.searchController.searchBar is nil when you setup constraints

Upvotes: 11

Related Questions