Home > Software design >  animateWithDuration can't animating UIButton's bounds after UIButton has set an image
animateWithDuration can't animating UIButton's bounds after UIButton has set an image

Time:12-10

After I had set an image to an UIButton called bigIcon, I put it inside animateWithDuration with the change of its frame, then I ran the code, the button size changed instantly (has no animation), but it move from origin to destination slowly (has animation), how can I solve this problem? I found out that if I did set an image to the button this problem will disappear.

here is the code:

- (void)bigImage:(MCGodCell *)godCell withImage:(UIImage *)image {
    self.bigIcon = [UIButton new];
    self.bigIcon.adjustsImageWhenHighlighted = NO;
    [self.bigIcon setBackgroundImage:image forState:UIControlStateNormal];

    CGFloat iconX = self.tableView.frame.size.width / 2.0;
    CGFloat iconY = self.tableView.frame.size.height / 2.0;
    self.bigIcon.frame = CGRectMake(iconX, iconY, 1, 1);
    [self.tableView addSubview:self.bigIcon];

    CGFloat iconW = self.tableView.frame.size.width;
    CGFloat iconH = iconW;
    iconY = (self.view.frame.size.height - iconH) / 2.0;
    [UIView animateWithDuration:0.3 animations:^{
        self.bigIcon.frame = CGRectMake(0, iconY, iconW, iconH);
    }];
}

CodePudding user response:

You're not seeing the frame change because you're trying to animate it immediately after adding it to the view hierarchy.

UIKit needs to add the button as a subview, and then run the animation on the next UI update pass.

Wrap your animation block inside a dispatch_async block like this:

dispatch_async(dispatch_get_main_queue(), ^{
    [UIView animateWithDuration:0.3 animations:^{
        self.bigIcon.frame = CGRectMake(0, iconY, iconW, iconH);
    }];
});
  • Related