我需要帮助创建一个带有子控制器表的下拉菜单。
示例代码:
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
的所有内容都不会显示动画。
尝试在动画块中添加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)
动画不会对你的selectCountry.view的子视图起作用,因为你只为selectCountry.view的框架设置动画,并且因为它的子视图的框架不是“相对”它的框架它们不会动画,这就是为什么你应该使用autoLayout,甚至是编程,至少要设置相对于selectCountry.view的子视图的约束,这样当它的帧改变时,它们将相应地改变