我有一个以编程方式定义的 UISegmentedControl。
我正在尝试添加布局约束,以便当我的 iPad 旋转时,分段控件在旋转 View 中正确调整大小,而不是溢出屏幕。
我应用了以下约束:
streamSegmentedControl.translatesAutoresizingMaskIntoConstraints = false
let segmentedControlWidth = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Width,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Width,
multiplier: 1.0,
constant: -10.0)
containerView.addConstraint(segmentedControlWidth)
我的 UIsegmentControl 定义如下:
streamSegmentedControl = UISegmentedControl(items: ["Today's Events", "Past Events"])
streamSegmentedControl.frame = CGRectMake(-10,containerView.frame.size.height*0.3,containerView.frame.width+20,40)
streamSegmentedControl.selectedSegmentIndex = 0
streamScope = "today"
streamSegmentedControl.setTitleTextAttributes(segmentedControlFont as [NSObject : AnyObject], forState: .Normal)
streamSegmentedControl.backgroundColor = UIColor.colorFromClass("background")
streamSegmentedControl.tintColor = UIColor.colorFromClass("default")
streamSegmentedControl.addTarget(self, action: "changeStreamScope:", forControlEvents: UIControlEvents.ValueChanged)
containerView.addSubview(streamTableView)
containerView.addSubview(streamSegmentedControl)
我没有收到错误,但在运行时,我的分段控件消失了。不确定我在这里遗漏了什么,因为我过去只在 Storyboard 中进行过自动布局。
我只想能够调整分段控件的宽度,所以我假设我只需要一个布局约束。
谁能给我一些指导?谢谢。
最佳答案
您至少需要添加三个约束。前导、顶部和尾随。 我在 swift 方面很弱,但你的约束应该是这样的。
let segmentedControlTop = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Top,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let segmentedControlLeading = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Leading,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
let segmentedControlTrailing = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Trailing,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Trailing,
multiplier: 1.0,
constant: 0.0)
containerView.addConstraint(segmentedControlTop)
containerView.addConstraint(segmentedControlLeading)
containerView.addConstraint(segmentedControlTrailing)
如果您想与 superview 保持 5 点偏移,请尝试使用 5 点的前导和尾随常数值。
关于swift - 给 UISegmentedControl 添加 NSLayoutConstraints 导致 UISegmentedControl 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32913840/