因?yàn)轫?xiàng)目要做到美觀,加上扁平化設(shè)計(jì)這么流行,所以各種找資料.
原本想找找UIButton是否有直接的設(shè)置方法,卻發(fā)現(xiàn)沒(méi)有.找到點(diǎn)擊后高亮也只有setBackgroundImage 這條路走了.
首先寫(xiě)一個(gè)能改變大小,顏色,返回值為image的類方法.(我在網(wǎng)上找的...)
+ (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,否則設(shè)置高亮不起作用
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom]; [btn.layer setMasksToBounds:YES]; [btn.layer setCornerRadius:4.0]; //設(shè)置矩形四個(gè)圓角半徑// [btn.layer setBorderWidth:1.0]; //邊框?qū)挾? btn.frame = frame; [btn setTitle:title forState:UIControlStateNormal]; [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//ButtonBgColor與ButtonTouchBgColor是兩個(gè)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;}
大家也可以根據(jù)CAlayer的屬性和方法,自定義喜歡的UIButton樣式.
?
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注