Swift 2如何展开和折叠视图?

时间:2016-12-12 09:36:41

标签: swift2 xcode8

我有scrollView,如果没有数据,我需要隐藏(折叠它占用的空间),以便下面的视图可以向上。

我试过这段代码没有运气。请帮帮我。

if(dataForScroll==0){

       var   newFrame:CGRect = self.myScroll.frame;

   newFrame.size.height = 0;
   self.myScroll.frame = newFrame



           }

1 个答案:

答案 0 :(得分:1)

使用Swift 3版本的一个简单示例,我认为它可能会解决您的问题。如果有任何疑问,请告诉我

 @IBOutlet var mainScrollView: UIScrollView!
 @IBOutlet var view1: UIView!
 @IBOutlet var view2: UIView!
 @IBOutlet var view3: UIView!

 var data1 = NSArray()
 var data2 = NSArray()
 var data3 = NSArray()

func setFrame()
{
  //  data = Something you need to get

    if data1.count == 0
    {
        self.view1.frame.size.height = 0
    }
    else
    {
       // return its actual height you need
    }
    if data2.count == 0
    {
        self.view2.frame.size.height = 0
    }
    else
    {
        // return its actual height you need
    }
    if data3.count == 0
    {
        self.view3.frame.size.height = 0
    }
    else
    {
        // return its actual height you need
    }

    var frame = self.view1.frame
    frame.origin.y = 5
    self.view1.frame = frame

    frame = self.view2.frame
    frame.origin.y = self.view1.frame.origin.y + self.view1.frame.size.height + 5
    self.view2.frame = frame

    frame = self.view3.frame
    frame.origin.y = self.view2.frame.origin.y + self.view2.frame.size.height + 5
    self.view3.frame = frame

    var scrollHeight:CGFloat = 0.0
    var contentRect:CGRect = CGRect.zero

    for views in self.mainScrollView.subviews
    {
        let subView:UIView = views
        contentRect = contentRect.union(subView.frame)
        print(subView.frame.size.height)
        scrollHeight = scrollHeight + subView.frame.size.height
    }

    self.mainScrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: scrollHeight + 20) // the "+ 20" reamains the spaces between the views, you can change as per your need
}