美文网首页iOS开发资料收集Swift开发实战
如何为UI控件在XIB和Storyboard添加属性

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

作者: sprint | 来源:发表于2016-01-04 11:53 被阅读1102次

    我不知道你有没有觉得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) 
      }
    }
    
    效果图

    相关文章

      网友评论

      本文标题:如何为UI控件在XIB和Storyboard添加属性

      本文链接:https://www.haomeiwen.com/subject/mpfahttx.html