将宽度/高度约束添加到您的视图,并将
constant
设置为0,将使
your View
的宽度和高度为0(就像
GONE
一样)。
// set the height constraint to 0
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:theGoneView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:0]];
// set the width constraint to 0
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:theGoneView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:0]];
在Swift中
let widthConstraint = NSLayoutConstraint(item: theGoneView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: theGoneView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)
view.addConstraint(heightConstraint)
或者使用这个UIView扩展
extension UIView {
func goAway() {
let widthConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0)
superview!.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 0)
superview!.addConstraint(heightConstraint)
}
}
希望这能帮到你。