Search code examples
iosuibuttonuiappearance

Set rounded corners globally on UIButtons in iOS application


Is there a way to set UIButtons with rounded corners globally like with color below?

[[UIButton appearance] setBackgroundColor:[UIColor purpleColor]];

Solution

  • #import <QuartzCore/QuartzCore.h>
    

    Add this in your header file.

    then in implementation,

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100, 100, 100,50);
    [btn setTitle:@"Hello" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor colorWithRed:128.0/255.0f green:0.0/255.0f  blue:0.0/255.0f alpha:0.7]];
    btn.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);//width and height should be same  value
    btn.clipsToBounds = YES;
    
    btn.layer.cornerRadius = 20;//half of the width
    btn.layer.borderColor=[UIColor redColor].CGColor;
    btn.layer.borderWidth=2.0f;
    

    cornerRadius will do the trick for you.. Let me know if more info needed.. :)

    Edit

    This cannot be achieved globally. As you used appearence, here is the list to see what you can customize with UIAppearance. what you can do is you can create a subclass of your UIButton, & there you can write implementation of setCornerRadius in initWithCoder Method.