How to animate preferredContentSize when using UIP

2019-07-21 05:22发布

I am able to successfully change the frame of a popover I present by simply setting preferredContentSize. I would now like to animate the change in the content size but I haven't been successful. It just instantly updates, in fact the delay I have set isn't even respected. How could one animate the change in content size?

//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)

1条回答
家丑人穷心不美
2楼-- · 2019-07-21 05:39

I was able to reproduce your problem, then figured out a way to make it work. The animation delay just isn't working here, so set that to 0 and do a different type of delay before doing the animation. I use a function I found here on SO:

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

Just put that at the top of any swift file, outside of the class definition.

Then change your code to look like this:

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)
})
查看更多
登录 后发表回答