如何为下拉菜单的显示设置动画?

时间:2019-04-12 08:43:57

标签: ios swift iphone xcode

我需要帮助,并使用子控制器中的表格创建下拉菜单。

示例代码:


class ParentViewController: UIViewController {


  func displayShowCountries() {

   if let textField = self.activeTextField, let superview = textField.superview {
       let convert = superview.convert(textField.frame, to: self.view)

       let row = viewModel.count - 1
       let indexPath = IndexPath(row: row, section: 0)
       guard let cell = tableView.cellForRow(at: indexPath) else { return }
       let cellConvert = tableView.convert(cell.frame, to: self.view)


       addChild(selectCountry)
       view.addSubview(selectCountry.view)
       selectCountry.didMove(toParent: self)

       // start frame
       selectCountry.view.frame = CGRect(x: convert.origin.x, y: convert.maxY, width: convert.width, height: 0)

       let height = (cellConvert.origin.y - convert.origin.y) + 8

       UIView.animate(
          withDuration: 0.3, 
          delay: 0, 
          usingSpringWithDamping: 1, 
          initialSpringVelocity: 1, 
          options: .curveEaseOut, 
          animations: {
               self.selectCountry.view.frame = CGRect(x: convert.origin.x, y: convert.maxY, width: convert.width, height: height)
          },
          completion: nil)
    }

  }
}

对于SelectCountry()

class SelectCountry: UIViewController {

   override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        tableView.frame = view.bounds
    }

}

动画仅适用于selectCountry.view,但是selectCountry.view中的所有动画都不会与动画一起显示。

2 个答案:

答案 0 :(得分:1)

尝试在动画块中添加self.view.layoutIfNeeded(),如下所示

 UIView.animate(
          withDuration: 0.3, 
          delay: 0, 
          usingSpringWithDamping: 1, 
          initialSpringVelocity: 1, 
          options: .curveEaseOut, 
          animations: {
               self.selectCountry.view.frame = CGRect(x: convert.origin.x, y: convert.maxY, width: convert.width, height: height)
    self.view.layoutIfNeeded()
          },
          completion: nil)

答案 1 :(得分:0)

动画无法在selectCountry.view的子视图上工作,因为您仅对selectCountry.view的帧进行了动画处理,并且由于其子视图的帧相对于其框架没有“动画”,因此为什么您应该使用autoLayout,即使在编程上也是如此,至少要设置相对于selectCountry.view的子视图的约束,这样,当其框架发生变化时,子视图的约束也将随之改变