Pregunta

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

[[UIButton appearance] setBackgroundColor:[UIColor purpleColor]];
¿Fue útil?

Solución 3

#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.

Otros consejos

The list of properties that you can set using UIAppearance is found here:

What properties can I set via an UIAppearance proxy?

Unfortunately rounded corners are not something that is possible.

You could use something like beautify (https://github.com/beautify/beautify-ios) which enhances the UIKit controls to allow you to specify rounded buttons.

With beautify, the following would give you rounded buttons globally:

BYTheme *theme = [BYTheme new];
theme.buttonStyle.border = [[BYBorder alloc] initWithColor:[UIColor blackColor]
                                                     width:2.0f
                                                    radius:5.0f];

[[BYThemeManager instance] applyTheme:theme];

I've found this link. Please see if it could help.

Taming UIButton

It is using this

[[basicButton layer] setCornerRadius:18.0f];

As i mentioned in previous answer. You have to subclass UiButton for it.. :)

Migrating advice for a workable solution to Swift (it's also possible using an equivalent ObjC category on UIView):

1. Add this extension https://gist.github.com/d3ce2e216884541217d0

2. Code:

let a = UIButton.appearance()
a.layerCornerRadius = 20.0
a.layerBorderColor = UIColor.redColor().CGColor
a.layerBorderWidth = 2.0

This sort of hack works because of how properties are copied. All appearance changes to things like a.layer and a.titleLabel are not propagated, but extension properties are copied.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top