프로그래밍/Xcode-iOS
iOS UIButton SetBackgroundColor forState:
Mr-후
2020. 4. 24. 18:13
반응형
예전에 네이버 블로그에 올렸던 포스팅인데 오늘 또 사용할 일이 있어서 찾아보니 보인다.
예전 포스팅은 UIButton Category Method로 작업을 했는데 이번에는 UIButton을 상속받아 TabBarItem을 하나 만들고 InitWithFrame할 때 아예 self의 setBackgroundColor와 같은 기능을 하는 setBackgroundImage:forState를 추가해서 만들도록 구현을 했다.
@implementation TabBarItem
/**
* 기본 UI버튼 생성
*/
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setTitleColor:_color(170, 170, 170) forState:UIControlStateNormal];
[self.titleLabel setFont:[UIFont systemFontWithType:FONT_SUB_TITLE of:12]];
[self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self setBgColor:_colorWithHexRGB(0xf7f7f7) forState:UIControlStateHighlighted];
}
return self;
}
/**
* state에 따라 배경색을 설정하는 메서드
*/
- (void)setBgColor:(UIColor *)color forState:(UIControlState)state {
UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
colorView.backgroundColor = color;
UIGraphicsBeginImageContext(colorView.bounds.size);
[colorView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self setBackgroundImage:colorImage forState:state];
}
@end
반응형