iOS 为xib,StoryBoard添加其他属性的一些方法
2016-10-11 本文已影响606人
Chowie
方法一
增加layer.borderWidth 和 layer.cornerRadius 属性
![](https://img.haomeiwen.com/i1633106/8de69736c36b6ae3.png)
增加borderUIColor属性时需要先增加一个分类
![](https://img.haomeiwen.com/i1633106/1a1f66afba27655a.png)
CALayer+XibConfiguration.h:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
@interface CALayer(XibConfiguration)
// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;
@end
CALayer+XibConfiguration.m:
#import "CALayer+XibConfiguration.h"
@implementation CALayer(XibConfiguration)
-(void)setBorderUIColor:(UIColor*)color
{
self.borderColor = color.CGColor;
}
-(UIColor*)borderUIColor
{
return [UIColor colorWithCGColor:self.borderColor];
}
@end
![](https://img.haomeiwen.com/i1633106/f747d012dce7de88.png)
In Swift 2.0:
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.CGColor
}
get {
return UIColor(CGColor: self.borderColor!)
}
}
}
方法二
You can make a category of UIView and add this in .h file of category
@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadius;
Now add this in .m file
@dynamic borderColor,borderWidth,cornerRadius;
and this as well in . m file
-(void)setBorderColor:(UIColor *)borderColor{
[self.layer setBorderColor:borderColor.CGColor];
}
-(void)setBorderWidth:(CGFloat)borderWidth{
[self.layer setBorderWidth:borderWidth];
}
-(void)setCornerRadius:(CGFloat)cornerRadius{
[self.layer setCornerRadius:cornerRadius];
}
now you will see this in your storyboard for all UIView subclasses (UILabel, UITextField, UIImageView etc)
![](https://img.haomeiwen.com/i1633106/854defa0b59352b4.png)
In Swift
import UIKit
@IBDesignable extension UIView {
@IBInspectable var borderColor:UIColor? {
set {
layer.borderColor = newValue!.CGColor
}
get {
if let color = layer.borderColor {
return UIColor(CGColor:color)
}
else {
return nil
}
}
}
@IBInspectable var borderWidth:CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius:CGFloat {
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
}