3

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?

Vijay S
  • 282
  • 2
  • 7
  • 15
Manish Malviya
  • 546
  • 2
  • 15
  • Your code seems fine! Are you using auto layout for designing? may be an issue in the auto layout constraints! – arunjos007 Apr 03 '18 at 05:04
  • yes am using auto layout and in storyboard everything seems fine no issues with constraints. Shocking stuff is that when I debug view from Xcode then all views are realign properly – Manish Malviya Apr 03 '18 at 07:09
  • Looks strange! Anyway, you can give it a try by clearing all the constraints and check what is the result – arunjos007 Apr 03 '18 at 13:48
  • image set aspectfit and clear constraint and again give them proper constraint. –  Apr 04 '18 at 04:01
  • Why are you calling [self setUpView]; so many times in different places ? this is bad practice. – GyroCocoa Apr 06 '18 at 15:29

1 Answers1

-2

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;

Shoaib
  • 2,286
  • 1
  • 19
  • 27