因為項目要做到美觀,加上扁平化設計這么流行,所以各種找資料.
原本想找找UIButton是否有直接的設置方法,卻發現沒有.找到點擊后高亮也只有setBackgroundImage 這條路走了.
首先寫一個能改變大小,顏色,返回值為image的類方法.(我在網上找的...)
+ (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; }
+ (instancetype)buttonWithTitleAndColor:(NSString *)title frame:(CGRect)frame{
//必須是UIButtonTypeCustom,否則設置高亮不起作用
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom]; [btn.layer setMasksToBounds:YES]; [btn.layer setCornerRadius:4.0]; //設置矩形四個圓角半徑// [btn.layer setBorderWidth:1.0]; //邊框寬度 btn.frame = frame; [btn setTitle:title forState:UIControlStateNormal]; [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//ButtonBgColor與ButtonTouchBgColor是兩個UIColor顏色的宏定義,大家可以隨意定義.例如[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;}
大家也可以根據CAlayer的屬性和方法,自定義喜歡的UIButton樣式.
?
|
新聞熱點
疑難解答