问题:我们需要给StoryBoard,xib里面控件
设置属性
,一般做法我们用拖拽,连线的方法关联起控件和关联的文件,然后在代码里面设置属性
,但是这样重复的操作大大的增加了开发时间和增加代码量,繁琐。
解决:那么,有没有可以直接在控件右侧属性界面
自定义属性,直接设置相关属性
,就像一个UIView直接可视化设置背景颜色一样,岂不乐哉?
下面分别就oc和swift介绍具体方法。
一:object-c
语言
1:IBInspectable
属性介绍
IBInspectable
写在属性前面,然后xib
上就会出现自定义添加的属性。
2:IBInspectable
属性使用场景
一般用于UIView
的继承
或者分类
。因为所有控件都是UIView
的子类,设置它的分类,其他所有控件都可以用。
3:IBInspectable
属性使用举例(分类)
IBInspectable
:添加属性,示例如下:文件和代码
#import <UIKit/UIKit.h>
@interface UIView (ViewAddtion)
///倒角
@property (nonatomic, assign) IBInspectable double xCornerRadius;
///边框颜色
@property (nonatomic, strong) IBInspectable UIColor *borderColor;
///边框宽度
@property (nonatomic, assign) IBInspectable double borderWidth;
@end
#import "UIView+ViewAddtion.h"
@implementation UIView (ViewAddtion)
- (void)setXCornerRadius:(double)xCornerRadius {
self.layer.cornerRadius = xCornerRadius;
self.layer.masksToBounds = YES;
}
- (double)xCornerRadius {
return self.layer.cornerRadius;
}
- (void)setBorderColor:(UIColor *)borderColor {
self.layer.borderColor = borderColor.CGColor;
}
- (UIColor *)borderColor {
return [UIColor colorWithCGColor:self.layer.borderColor];
}
- (void)setBorderWidth:(double)borderWidth {
self.layer.borderWidth = borderWidth;
}
- (double)borderWidth {
return self.layer.borderWidth;
}
@end
最终效果: xib或者storyboard中新增了三个属性:
image.png
二:swift
语言
1:需要用到IBDesignable
,此类可以被nib识别使用
2:需要用到IBInspectable
,此属性可以被nib使用
3:MyView类继承与UIView,下面是类中实现的主要代码
import UIKit
//@IBDesignable告诉编译器,此类可以被nib识别使用
@IBDesignable class MyView: UIView {
//@IBInspectable告诉编译器,此属性可以被nib使用
@IBInspectable var borderWidth : CGFloat = 0{
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor : UIColor = UIColor.clearColor(){
didSet{
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var xCornerRadius : CGFloat = 0 {
didSet{
layer.cornerRadius = xCornerRadius
}
}
}
最终效果: xib或者storyboard中新增了三个属性:
image.png