我希望标题清楚.我想隐藏一个元素(在我的情况下是数据选择器),我也想隐藏他的空间.
所以我用动画尝试了这个:
所以我用动画尝试了这个:
- @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,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,constant: 0)
- //self.pickerQnt.addConstraint(constH)
- })
- }
- }
我也尝试过类似的东西:
- self.pickerQnt.hidden = true
但不会工作.
提前致谢.
解决方法
在Objective-C / Swift中使用
“hidden” property视图实际上不会“崩溃”视图所占用的空间(与
“View.GONE” in Android相反).
相反,您应该使用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()
- }
- }
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];
- }
- }
免责声明:我没有测试或编译上面的代码,但它会让你知道如何实现它.
重要信息:上面的代码假定您在故事板/笔尖中为选取器视图的高度约束赋予大于0的值.