Do you want to make a solid UIButton? Come, teach you ~, Solid color uibutton
Because the project needs to be beautiful, and the flat design is so popular, various materials should be found.
I originally wanted to check whether UIButton has a direct setting method, but I found that there is no. After I click it, I can only highlight setBackgroundImage.
First, write a class method that can change the size, color, and return value as image. (I found it online ...)
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size { CGRect rect = CGRectMake(0, 0, size.width, size.height); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
Well, I wrote the following and shared it with you:
+ (instancetype)buttonWithTitleAndColor:(NSString *)title frame:(CGRect)frame{
// It Must Be UIButtonTypeCustom; otherwise, setting the highlight does not work.
UIButton * btn = [UIButton buttonWithType: UIButtonTypeCustom]; [btn. layer setMasksToBounds: YES]; [btn. layer setCornerRadius: 4.0]; // set the radius of the four rounded corners of the rectangle. // [btn. layer setBorderWidth: 1.0]; // Border Width btn. frame = frame; [btn setTitle: title forState: UIControlStateNormal]; [btn setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
// ButtonBgColor and ButtonTouchBgColor are two macro definitions of UIColor. You can define them at will. For example, [UIColor blueColor];
UIImage * bgImage1 = [self imageWithColor:ButtonBgColor size:frame.size]; UIImage * bgImage2 = [self imageWithColor:ButtonTouchBgColor size:frame.size]; [btn setBackgroundImage:bgImage1 forState:UIControlStateNormal]; [btn setBackgroundImage:bgImage2 forState:UIControlStateHighlighted]; return btn;}
You can also customize your favorite UIButton style based on CAlayer attributes and methods.