首页 文章

如何以编程方式向UISegmentedControl添加约束

提问于
浏览
2

这是我的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员工守护者[14424:11105086] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** [NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]:乘数0或零秒项以及位置第一个属性创建一个等于常量的位置的非法约束 . 必须成对指定位置属性'*** First throw call stack:

我究竟做错了什么?

1 回答

  • 4

    我认为这是因为你设置约束时你的 self.searchController.searchBar 是零

相关问题