imageview.transform inside UIButton subclass strange behaviour

212 Views Asked by At

I had made an UIButton subclass and had added an IBInspectable property that rotates the imageView inside UIButton. In InterfaceBuilder all seems to work perfect but at runtime, it's behaving strangely.

Here's my code

MyButton.m

@implementation MyButton



-(void)awakeFromNib{
    [super awakeFromNib];
    [self setUpView];
}

-(void)layoutSubviews{
    [self setUpView];
    [super layoutSubviews];

}


-(void)prepareForInterfaceBuilder{
    [self setUpView];
}

-(void)setUpView{

    self.transform = CGAffineTransformMakeRotation(self.angle * M_PI / 180.0);
}

@end

It looks like below in Main.storyboard

Series of custom button rotated to look like teeth inside mouth

What I did here is I had used 32 MyButton to make it look like teeth.

But at runtime, it looks like this

Series of custom button rotated to look like teeth inside the mouth at runtime

What I tried is :

  1. I had commented

    self.imageView.transform = CGAffineTransformMakeRotation(self.angle * M_PI / 180.0);
    

then button gets proper height width but is not looking good since they require rotation

  1. I had changed my code to

     self.transform = CGAffineTransformMakeRotation(self.angle * M_PI / 180.0);
    

and it worked somewhat.

So is there something I am missing or am I doing something wrong?

1

There are 1 best solutions below

3
Shoaib On

I think the problem is order. calling layoutSubviews after setUpView, disturbing the UIImageView.

So try just a small fix. change your layout subviews method with this;

-(void)layoutSubviews{
    [super layoutSubviews]; // Supper layoutSubviews should be on top
    [self setUpView]; // and then customization
}

so now you should be able to transform your imageView like this;

self.imageView.transform = CGAffineTransformMakeRotation(self.angle * M_PI / 180.0);

Thanks;