6

How to properly animate datePicker appearance/disappearance in stackView? Currently I tried like this:

UIView.animateWithDuration(0.3, animations: {
    self.datePickerView.hidden = !self.datePickerView.hidden
})

This causes problems with hiding animation - it starts nicely and then in the end datePickerView flashes a little bit at the top of where datePicker was. Any suggestions?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Xernox
  • 1,706
  • 1
  • 23
  • 37

2 Answers2

10

I had the same issue and solved it this way:

  • Put your Picker in a view (we will call it pickerContainerView)
  • Set a 216 height constraint to your pickerContainerView (picker default height)
  • Set the constraint priority to 999 to quiet "UISV-hiding" constraint warning
  • Add "leading", "trailing" and "center vertically" constraints from your picker to the pickerContainerView
  • animate hide of the pickerContainerView :

Swift 2

UIView.animateWithDuration(0.3, animations: {
    self.pickerContainerView.hidden = !self.pickerContainerView.hidden
})

Swift 3, 4, 5

UIView.animate(withDuration: 0.3, animations: {
    self.pickerContainerView.isHidden = !self.pickerContainerView.isHidden
})

Views tree

Karen Hovhannisyan
  • 1,140
  • 2
  • 21
  • 31
Panda
  • 116
  • 2
  • 5
  • 4
    I tried this solution, but I didn't like the animation. The datePicker height does not decrease, it just disappears after a delay, which is weird. – Frederic Adda Feb 24 '17 at 08:27
  • 2
    @FrédéricAdda if you want better animation just pin UIDatePicker.topAnchor to picker container topAnchor and remove vertical center contstraint for UIDatePicker. This will produce animation that looks like covering UIDatePicker instead of moving and shrinking (like in posted gif). – Palli May 09 '19 at 06:23
0

Using a container to hold the picker and setting clipsToBounds = true worked for me.

I'm using PureLayout, but it should work with IB too.

startRangePickerContainer = UIView()
startRangePickerContainer.clipsToBounds = true
startRangePickerContainer.backgroundColor = UIColor.cyan
stackView.addArrangedSubview(startRangePickerContainer)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .leading)
startRangePickerContainer.autoSetDimension(.height, toSize: 216)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .leading)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .trailing)

startRangePicker = UIDatePicker()
startRangePickerContainer.addSubview(startRangePicker)
startRangePicker.autoCenterInSuperview()

To animate:

UIView.animate(withDuration: 0.3, animations: {
    self.startRangePickerContainer.isHidden = !self.startRangePickerContainer.isHidden
})