使用 UIPopoverPresentationController 时如何为 preferredContentSize 设置动画?

How to animate preferredContentSize when using UIPopoverPresentationController?

我可以通过简单地设置 preferredContentSize 来成功更改我显示的弹出窗口的框架。我现在想为内容大小的变化设置动画,但我没有成功。它只是立即更新,事实上我设置的延迟甚至没有得到尊重。如何动画化内容大小的变化?

//In viewDidAppear:
UIView.animateWithDuration(5, delay: 3, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
    self.preferredContentSize = CGSizeMake(320, 400)
}, completion: nil)

我重现了您的问题,然后找到了解决问题的方法。动画延迟在这里不起作用,因此将其设置为 0 并在执行动画之前执行不同类型的延迟。我使用在 SO 上找到的函数:

func delay(delay: Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

只要把它放在 swift 文件的顶部,在 class 定义之外。

然后将您的代码更改为如下所示:

delay(3, { () -> () in
    UIView.animateWithDuration(5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
        self.preferredContentSize = CGSizeMake(320, 400)
        }, completion: nil)
})