4
votes

I have a UIButton (created in interface builder), that I'm turning into a circle by setting button.layer.borderRadius = button.frame.size.width / 2.0; (programatically, in viewDidAppear:). However, the viewController it belongs to is presented modally with an animation. Since viewDidAppear isn't called until after the transition animation has finished, the button is square until then, which makes the sudden change quite jarring.

I can't set the radius in viewDidLoad, since the button properties are incorrect then (the width is too large), which I think is because autolayout constraints haven't been properly resolved yet. I tried to rectify this by calling [self.view setNeedsLayout] in viewDidLoad, and then setting the cornerRadius, but the button width was still wrong. What I don't understand is, during the animation, everything otherwise renders correctly, suggesting that the autolayout constraints /have/ been resolved, or that iOS does something else in the name of quick animations (like storing a snapshot preview to use for the animation).

Any suggestions?

The result of trying to set the corner radius in viewDidLoad:

The result of trying to set the corner radius in viewDidLoad

5

5 Answers

6
votes

You can get the width in the function - viewDidLayoutSubviews.

Apple Documentation here.

3
votes

Override the UIButton and make its layoutSubviews method like this:

- (void)layoutSubviews {
    [super layoutSubviews];
    self.layer.cornerRadius = self.bounds.size.width/2.f;
}

Then whenever the button's size changes it will adjusts its value. Also add it in buttonWithType: and initWithFrame: as I'm not sure if the layoutSubviews is called after init.

0
votes

Your controls get the constraints and frame set after viewDidLoad amd after viewDidLoad you can get your requirements in viewwilllayoutsubviews or in viewdidlayoutsubviews before viewDidAppear

0
votes

what about

-(void) viewWillAppear:(BOOL)animated
0
votes

Sorry I didn't get you well. As your screenshot explains that your image isn't being circular.For that you can try:(1) layer.cornerRadius = btn.frame.size.width/2; or layer.CornerRadius = 50(if width is 100)

 layer.masksToBounds = YES;

 layer.borderWidth = 1.5; or whatever you want

 layer.borderColor = [UIColor whiteColor];

If still you get problem, then share your constraints that you added on button and also the code where you are doing this.