如何通过编程向UISegmentedControl添加约束条件

3

这是我的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))

您可以看到,我正在为 UISegmentedControl 添加约束条件,但是我的应用程序崩溃了。以下是错误消息:

2015-09-03 18:50:52.241 Employee Keeper[14424:11105086] * 由于未捕获的 NSInvalidArgumentException 异常终止应用程序,原因:'* + [NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]:0 的乘数或空值二次项与第一个属性的位置一起创建一个非法约束,该位置等于一个常量。位置属性必须成对指定' *** 第一个抛出调用堆栈:

我做错了什么?

1个回答

11
我认为原因在于您设置约束时self.searchController.searchBar为空。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接