Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UIButton width before viewDidAppear, with AutoLayout

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

like image 576
user2589494 Avatar asked Jan 07 '23 15:01

user2589494


2 Answers

You can get the width in the function - viewDidLayoutSubviews.

Apple Documentation here.

like image 83
Shamas S Avatar answered Jan 14 '23 07:01

Shamas S


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.

like image 41
Alistra Avatar answered Jan 14 '23 06:01

Alistra