以编程方式应用自动布局时标签消失-iOS Swift
说明: 在我的ViewController中,我希望根据单选按钮以编程方式创建和调整视图。当我以编程方式创建视图和设置约束时,会出现一个问题,其中一个标签会消失,如果我继续使用该标签,ViewController中的大多数组件会消失并移动 图片:以编程方式应用自动布局时标签消失-iOS Swift,ios,swift,autolayout,Ios,Swift,Autolayout,说明: 在我的ViewController中,我希望根据单选按钮以编程方式创建和调整视图。当我以编程方式创建视图和设置约束时,会出现一个问题,其中一个标签会消失,如果我继续使用该标签,ViewController中的大多数组件会消失并移动 图片: func serviceHoursRadioButtonAction(button: DLRadioButton) { if button.currentTitle == "yes" { serviceHoursView = U
func serviceHoursRadioButtonAction(button: DLRadioButton) {
if button.currentTitle == "yes" {
serviceHoursView = UIView()
if let myView = serviceHoursView {
myView.backgroundColor = UIColor.lightGrayColor()
view.addSubview(myView)
NSLayoutConstraint(item: myView,
attribute: .Top,
relatedBy: .Equal,
toItem: serviceHoursLabel,
attribute: .Bottom,
multiplier: 1, constant: 10).active = true
NSLayoutConstraint(item: myView,
attribute: .LeftMargin,
relatedBy: .Equal,
toItem: self.view,
attribute: .LeftMargin,
multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: myView,
attribute: .RightMargin,
relatedBy: .Equal,
toItem: self.view,
attribute: .RightMargin,
multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: myView,
attribute: .BottomMargin,
relatedBy: .Equal,
toItem: self.view,
attribute: .BottomMargin,
multiplier: 1, constant: 0).active = true
}
} else {
//do nothing, or remove the created view if any.
}
}
代码:
func serviceHoursRadioButtonAction(button: DLRadioButton) {
if button.currentTitle == "yes" {
serviceHoursView = UIView()
if let myView = serviceHoursView {
myView.backgroundColor = UIColor.lightGrayColor()
view.addSubview(myView)
NSLayoutConstraint(item: myView,
attribute: .Top,
relatedBy: .Equal,
toItem: serviceHoursLabel,
attribute: .Bottom,
multiplier: 1, constant: 10).active = true
NSLayoutConstraint(item: myView,
attribute: .LeftMargin,
relatedBy: .Equal,
toItem: self.view,
attribute: .LeftMargin,
multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: myView,
attribute: .RightMargin,
relatedBy: .Equal,
toItem: self.view,
attribute: .RightMargin,
multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: myView,
attribute: .BottomMargin,
relatedBy: .Equal,
toItem: self.view,
attribute: .BottomMargin,
multiplier: 1, constant: 0).active = true
}
} else {
//do nothing, or remove the created view if any.
}
}
将视图属性TranslateAuthoreSizingMaskinToConstraints设置为false。设置为
self.view.layoutSubviews()
修复了我的错误