ios – Swift如何隐藏元素和他的空间

前端之家收集整理的这篇文章主要介绍了ios – Swift如何隐藏元素和他的空间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望标题清楚.我想隐藏一个元素(在我的情况下是数据选择器),我也想隐藏他的空间.
所以我用动画尝试了这个:
  1. @IBAction func showQnt(sender: AnyObject) {
  2. if (self.pickerQnt.alpha == 0.0){
  3. UIView.animateWithDuration(0.2,delay: 0.0,options: UIViewAnimationOptions.ShowHideTransitionViews,animations: {
  4. self.pickerQnt.alpha = 1.0
  5.  
  6.  
  7. },completion: {
  8. (finished: Bool) -> Void in
  9. //var constH = NSLayoutConstraint(item: self.pickerQnt,attribute: NSLayoutAttribute.Height,relatedBy: NSLayoutRelation.Equal,toItem: nil,attribute: NSLayoutAttribute.NotAnAttribute,multiplier: 1,constant: 162)
  10. //self.pickerQnt.addConstraint(constH)
  11. })
  12. } else {
  13. UIView.animateWithDuration(0.2,animations: {
  14. self.pickerQnt.alpha = 0.0
  15.  
  16.  
  17. },completion: {
  18. (finished: Bool) -> Void in
  19. // CHECK: ?!? constrain to set view height to 0 run time
  20. //var constH = NSLayoutConstraint(item: self.pickerQnt,constant: 0)
  21. //self.pickerQnt.addConstraint(constH)
  22. })
  23. }
  24. }

我也尝试过类似的东西:

  1. self.pickerQnt.hidden = true

但不会工作.

提前致谢.

解决方法

在Objective-C / Swift中使用 “hidden” property视图实际上不会“崩溃”视图所占用的空间(与 “View.GONE” in Android相反).

相反,您应该使用Autolayout和高度约束.

在Xib / Storyboard文件中创建高度约束.给它希望的高度.为该约束创建一个IBOutlet(从Constraints列表中的Constraint拖动到源文件),然后你可以编写这个方法

迅捷解决方

  1. var pickerHeightVisible: CGFloat!
  2. ...
  3. ...
  4. func togglePickerViewVisibility(animated: Bool = true) {
  5. if pickerHeightConstraint.constant != 0 {
  6. pickerHeightVisible = pickerHeightConstraint.constant
  7. pickerHeightConstraint.constant = 0
  8. } else {
  9. pickerHeightConstraint.constant = pickerHeightVisible
  10. }
  11. if animated {
  12. UIView.animateWithDuration(0.2,animations: {
  13. () -> Void in
  14. self.view.layoutIfNeeded()
  15. },completion: nil)
  16. } else {
  17. view.layoutIfNeeded()
  18. }
  19. }

Objective-C解决方案:

  1. @property (nonatomic,strong) CGFloat pickerHeightVisible;
  2. ...
  3. ...
  4. - (void)togglePickerViewVisibility:(BOOL)animated {
  5. if(pickerHeightConstraint.constant != 0) {
  6. pickerHeightVisible = pickerHeightConstraint.constant;
  7. pickerHeightConstraint.constant = 0;
  8. } else {
  9. pickerHeightConstraint.constant = pickerHeightVisible;
  10. }
  11. if(animated) {
  12. [UIView animateWithDuration:0.2
  13. animations:(void (^)(void))animations:^(void) {
  14. [self.view layoutIfNeeded];
  15. }];
  16. } else {
  17. [self.view layoutIfNeeded];
  18. }
  19. }

免责声明:我没有测试或编译上面的代码,但它会让你知道如何实现它.

重要信息:上面的代码假定您在故事板/笔尖中为选取器视图的高度约束赋予大于0的值.

猜你在找的iOS相关文章