我希望标题清楚.我想隐藏一个元素(在我的情况下是数据选择器),我也想隐藏他的空间.所以我用动画尝试了这个:
@IBAction func showQnt(sender: AnyObject) {
if (self.pickerQnt.alpha == 0.0){
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.ShowHideTransitionViews, animations: {
self.pickerQnt.alpha = 1.0
}, completion: {
(finished: Bool) -> Void in
//var constH = NSLayoutConstraint(item: self.pickerQnt, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 162)
//self.pickerQnt.addConstraint(constH)
})
} else {
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.ShowHideTransitionViews, animations: {
self.pickerQnt.alpha = 0.0
}, completion: {
(finished: Bool) -> Void in
// CHECK: ?!? constrain to set view height to 0 run time
//var constH = NSLayoutConstraint(item: self.pickerQnt, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)
//self.pickerQnt.addConstraint(constH)
})
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过类似的东西:
self.pickerQnt.hidden = true
Run Code Online (Sandbox Code Playgroud)
但不会工作.
提前致谢.
这是一个老问题,但有另一个选项可用于较新的 iOS 版本:
如果您的布局允许,并且您的目标是iOS9 或更高版本,您可以将视图UIStackView作为容器排列在 a中。隐藏时堆栈视图的子级会折叠,即不再占用任何空间。
动态更改堆栈视图的内容
每当视图被添加、删除或插入到排列的子视图数组中,或者当排列的子视图的 isHidden 属性之一发生变化时,堆栈视图都会自动更新其布局。
( https://developer.apple.com/documentation/uikit/uistackview#overview )
在Objective-C/Swift中对视图使用"hidden"属性实际上不会"折叠"视图所占用的空间(而不是Android中的"View.GONE").
相反,您应该使用Autolayout和高度约束.
在Xib/Storyboard文件中创建高度约束.给它希望的高度.为该约束创建一个IBOutlet(从Constraints列表中的Constraint拖动到源文件),然后你可以编写这个方法
迅捷解决方案
var pickerHeightVisible: CGFloat!
...
...
func togglePickerViewVisibility(animated: Bool = true) {
if pickerHeightConstraint.constant != 0 {
pickerHeightVisible = pickerHeightConstraint.constant
pickerHeightConstraint.constant = 0
} else {
pickerHeightConstraint.constant = pickerHeightVisible
}
if animated {
UIView.animateWithDuration(0.2, animations: {
() -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
} else {
view.layoutIfNeeded()
}
}
Run Code Online (Sandbox Code Playgroud)
Objective-C解决方案:
@property (nonatomic, strong) CGFloat pickerHeightVisible;
...
...
- (void)togglePickerViewVisibility:(BOOL)animated {
if(pickerHeightConstraint.constant != 0) {
pickerHeightVisible = pickerHeightConstraint.constant;
pickerHeightConstraint.constant = 0;
} else {
pickerHeightConstraint.constant = pickerHeightVisible;
}
if(animated) {
[UIView animateWithDuration:0.2
animations:(void (^)(void))animations:^(void) {
[self.view layoutIfNeeded];
}];
} else {
[self.view layoutIfNeeded];
}
}
Run Code Online (Sandbox Code Playgroud)
免责声明:我没有测试或编译上面的代码,但它会让你知道如何实现它.
重要信息:上面的代码假定您在故事板/笔尖中为选取器视图的高度约束赋予大于0的值.