简体   繁体   中英

Background size with UIButton containing image above the text

I have an image displaying correctly above the text and the selected background is the correct size thanks to a wee hack (looping over the subviews).

The problem is with the coloured background springing back to the frame of the text, and then animating back to the correct size.

How can I prevent this strange background animation?

在此处输入图片说明

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat marginTop = 0;
    CGFloat marginBottom = 0;

    CGSize titleSize = self.titleLabel.frame.size;
    self.imageEdgeInsets = UIEdgeInsetsMake(  - (titleSize.height - marginTop),
                                              0.0,
                                              0.0,
                                              - titleSize.width);

    CGSize imageSize = self.imageView.frame.size;
    self.titleEdgeInsets = UIEdgeInsetsMake(  0.0,
                                              - imageSize.width,
                                              - (imageSize.height - marginBottom),
                                              0.0);

    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIImageView class]] && ![view isEqual:self.imageView]) {
            view.frame = self.bounds;
        }
    }
}

I think some animation is committed at somewhere. As you are using some view-hierarchy hack, then it might be hidden.

Try to avoid animation by calling setAnimationsEnabled: method.

   [UIView setAnimationsEnabled:NO];
   for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIImageView class]] && ![view isEqual:self.imageView]) {
            view.frame = self.bounds;
        }
    }
   [UIView setAnimationsEnabled:YES];

Beware. This is another hack based on global state, and may cause even worse side effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM