2017-07-15 135 views

回答

1

你可以使用这个滚动视图代表。例如,

func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    if scrollView.panGestureRecognizer.translation(in: scrollView.superview).y > 0 { 
     //scrolling downwards 
     if scrollView.contentOffset.y < 0 { 
      //this means we are at top of the scrollView 
      changeSectionHeight(with scrollView.contentOffset.y, hide:false) 
     } 
    } 
    else { 
     //we are scrolling upward 
     changeSectionHeight(with scrollView.contentOffset.y, hide:true) 
    } 
} 

这是用户如何滚动向下或向上滚动的方式。现在基于此,我们可以隐藏或显示顶部部分(通过更改高度约束)。

//make IBoutlet for the top section height constraint 
@IBOutlet weak var topSectionHeightConstraint: NSLayoutConstraint! 

func changeSectionHeight(with offset:CGFloat, hide:Bool) { 

    let requiredHeight: CGFloat = hide ? 0.0 : 160.0 //let say when you want to hide the height is 0.0 and when you want to show it its 160.0 

    //If you want animation when showing and hiding use animate if not then simply change the constant for the constraint 
    if hide { 
     if (holderViewHeightConstraint.constant - offset) > requiredHeight { 
      UIView.animate(withDuration: 0.3, animations: { 
       self. topSectionHeightConstraint.constant -= offset 
      }) 
     } 
     else { 
      UIView.animate(withDuration: 0.3, animations: { 
       self. topSectionHeightConstraint.constant = requiredHeight 
      }) 
     } 
    } 
    else { 
     if (holderViewHeightConstraint.constant - offset) < requiredHeight { 
      UIView.animate(withDuration: 0.3, animations: { 
       self. topSectionHeightConstraint.constant -= offset 
      }) 
     } 
     else { 
      UIView.animate(withDuration: 0.3, animations: { 
       self. topSectionHeightConstraint.constant = requiredHeight 
      }) 
     } 
    } 
} 
+0

如何在代码中更改高度约束? – Riccardo

+0

增加了改变高度的功能。没有测试,但你可以调整你想要的结果。 – kathayatnk