不需要一句代碼抚岗,給UI控件設(shè)置圓角和陰影及1px的兼容
- 在看這篇文章之前 請先參看IBInspectable 和 IB_DESIGNABLE
- 在Xib中 系統(tǒng)自帶的UI控件中 添加一些 額外的屬性
-
eg:
-
效果
示例代碼:
特別注意:
如果想實(shí)時(shí)監(jiān)聽MBIBnspectable的改變的話,需要繼承一個(gè)空的基類,或者自定義的類。
如果需要的話請繼承于PXBaseView.h
- UIView的xib擴(kuò)展
- .h文件
#import <UIKit/UIKit.h>
IB_DESIGNABLE
/** View的XIB可視化擴(kuò)展類> */
@interface UIView (IBnspectable)
/*!
* 給UIView 設(shè)置圓角
*/
@property (assign,nonatomic) IBInspectable NSInteger cornerRadius;
@property (assign,nonatomic) IBInspectable BOOL masksToBounds;
/*!
* 設(shè)置 view的 邊框顏色(選擇器和Hex顏色)
* 以及 邊框的寬度
*/
@property (assign,nonatomic) IBInspectable NSInteger borderWidth;
@property (strong,nonatomic) IBInspectable NSString *borderHexRgb;
@property (strong,nonatomic) IBInspectable UIColor *borderColor;
/*!
* 設(shè)置view的背景Hex顏色 (選擇器顏色 是系統(tǒng)自帶的不需要寫)
*/
@property (assign,nonatomic) IBInspectable NSString *hexRgbColor;
//TODO: 特別注意
/*!
* 這個(gè)屬性可以開啟 Retina屏對 1px的支持
* Retain屏的分辨率 [UIScreen mainScreen].scale分辨率是 >=2
*
*/
@property (assign,nonatomic) IBInspectable BOOL onePx;
@end
- .m文件的實(shí)現(xiàn)
@implementation UIView (IBnspectable)
- (void)setCornerRadius:(NSInteger)cornerRadius{
self.layer.cornerRadius = cornerRadius;
self.layer.masksToBounds = cornerRadius > 0;
}
- (NSInteger)cornerRadius{
return self.layer.cornerRadius;
}
- (void)setBorderWidth:(NSInteger)borderWidth{
self.layer.borderWidth = borderWidth;
}
- (NSInteger)borderWidth{
return self.layer.borderWidth;
}
- (void)setBorderColor:(UIColor *)borderColor{
self.layer.borderColor = borderColor.CGColor;
}
- (UIColor *)borderColor{
return [UIColor colorWithCGColor:self.layer.borderColor];
}
- (void)setBorderHexRgb:(NSString *)borderHexRgb{
NSScanner *scanner = [NSScanner scannerWithString:borderHexRgb];
unsigned hexNum;
//這里是將16進(jìn)制轉(zhuǎn)化為10進(jìn)制
if (![scanner scanHexInt:&hexNum])
return;
self.layer.borderColor = [self colorWithRGBHex:hexNum].CGColor;
}
-(NSString *)borderHexRgb{
return @"0xffffff";
}
- (void)setMasksToBounds:(BOOL)bounds{
self.layer.masksToBounds = bounds;
}
- (BOOL)masksToBounds{
return self.layer.masksToBounds;
}
#pragma mark - hexRgbColor
- (void)setHexRgbColor:(NSString *)hexRgbColor{
NSScanner *scanner = [NSScanner scannerWithString:hexRgbColor];
unsigned hexNum;
if (![scanner scanHexInt:&hexNum]) return;
self.backgroundColor = [self colorWithRGBHex:hexNum];
}
- (UIColor *)colorWithRGBHex:(UInt32)hex {
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;
return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:1.0f];
}
- (NSString *)hexRgbColor{
return @"0xffffff";
}
#pragma mark - setOnePx
- (void)setOnePx:(BOOL)onePx{
if (onePx) {
CGRect rect = self.frame;
rect.size.height = 5/ [UIScreen mainScreen].scale;
self.frame = rect;
}
}
- (BOOL)onePx{
return self.onePx;
}
@end