如何为UI控件在XIB和Storyboard添加属性

我不知道你有没有觉得XIB和Storyboard提供操作View的属性还是很少 ,比如XIB中不支持为UITextField设置padding,不支持在XIB中UIImageView设置圆角... 而iOS8中为我们带来了新的可能。

IBDesignable/IBInspectable

IBDesignable/IBInspectable 是IOS8为我们提供的新特性,支持自定义属性映射到XIB(运行时机制) 下面是依UITextField举例:

Objective-C IBDesignable/IBInspectable

自定义UITextField的子类,并将自定义的属性用IBInspectable标识

#import <UIKit/UIKit.h>
@interface IB_UITextField : UITextField
@property (nonatomic, assign)IBInspectable CGFloat cornerRadius;
@property (nonatomic, assign)IBInspectable CGFloat Padding;
@end

实现

IB_DESIGNABLE
@implementation IB_UITextField

- (void)setCornerRadius:(CGFloat)cornerRadius{
      _cornerRadius = cornerRadius;
    self.layer.cornerRadius  = _cornerRadius;
    self.layer.masksToBounds = YES;
}

-(CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, _Padding, _Padding);
}

-(CGRect)editingRectForBounds:(CGRect)bounds { 
     return [self textRectForBounds:bounds];
}
@end

Swift IBDesignable/IBInspectable

import UIKit@IBDesignableclass FormTextField: UITextField { 

  @IBInspectable var Padding: CGFloat = 0

 override func  textRectForBounds(bounds: CGRect) -> CGRect {
       return CGRectInset(bounds, Padding, Padding) 
  }

 override func editingRectForBounds(bounds: CGRect) -> CGRect {
       return textRectForBounds(bounds) 
  }
}
效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容