前言:

用storyboard/xib搞项目时,一些属性在Interface Builder上时无法设置,比如常用的layer的一些属性
cornerRadius,borderColor等 (有时没必须的关联属性 用代码去设置)。估计大家也都想省事,能Interface Builder解决的绝不代码(特殊情况外),搞个复杂点的界面加上约束条件,我x还不疯了 时间都玩它了。但是wwdc2014其中要解决的问题时:

  • 写的code怎么在Interface Builder动态预览效果?
  • code中的属性是否可以在Interface Builder上设置?

上边的2个问题就是这篇文章要解决的了:也就是在xcode6中苹果给提供了@IBDesignable和@IBInspectable   这里时必须时UIView/NSView子类使用,看到这可能要冒出 :“No Code you say a JB a”

例子1:那么废话少说直接先swift为例drawRect看下效果(注:UIView/NSView):

@IBDesignable   // 记得@IBDesignable添加 它就是告诉IB可以动态预览
class SView: UIView {

override func drawRect(rect:CGRect) {
         var context:CGContextRef = UIGraphicsGetCurrentContext()
         CGRectInset(CGRectMake(0, 0, 30, 30), 5, 5)
         UIColor.yellowColor().set()
         CGContextSetLineWidth(context, 22)
         UIRectFrame(CGRectMake(0, 0, 30, 30))
   }
}

那么就直接看下效果吧:

例子2: 怎么在CustomView上的子视图的属性在IB上设置呢?:

class DrawView: UIView {

var runLabel: UILabel!
       @IBInspectable var labelTitle: String!
       @IBInspectable var labelColor: UIColor!

override init(frame: CGRect) {
           super.init(frame: frame)

labelTitle = "一起扯扯"
           labelColor = UIColor.blackColor()
           runLabel = UILabel(frame:CGRectMake(0, 0, 180, 80))
           runLabel.textColor = labelColor
           runLabel.text      = labelTitle
           addSubview(runLabel)
     }

required init(coder aDecoder: NSCoder) {
     super.init(coder: aDecoder)

labelTitle = "一起扯扯"
          labelColor = UIColor.blackColor()
          runLabel = UILabel(frame:CGRectMake(0, 0, 180, 80))
          runLabel.textColor = labelColor
          runLabel.text      = labelTitle
          addSubview(runLabel)
     }

override func layoutSubviews() {
          runLabel.textColor = labelColor
          runLabel.text      = labelTitle
     }
}

那么就看下自定义的DrawView在IB上Label属性设置效果:

例子3: 怎么在IB上设置layer的一些属性值呢?

@IBDesignable
class SView: UIView {

@IBInspectable var cornerRadius: CGFloat = 0 {
             didSet {
                   layer.cornerRadius = cornerRadius
             }
      }

@IBInspectable var borderWidth: CGFloat = 0 {
             didSet {
                   layer.borderWidth = borderWidth
             }
     }

@IBInspectable var borderColor: UIColor? {
             didSet {
                   layer.borderColor = borderColor?.CGColor
             }
     }
}

在User Defined Runtime Attributes 中KeyPath不用自己填写,在设置的时候会自动填充上!还是看下效果吧:

例子4: 看到这里可能还会说是不是每个视图用到layer都这么费劲?答案:不会的 搞个UIView扩展就省事多点了!

extension UIView {
    @IBInspectable var cornerRadius: CGFloat {
         get {
            return layer.cornerRadius
         }
         set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
          }
    }

@IBInspectable var borderColor:CGColor {

get {
           return layer.borderColor
        }
        set {
          layer.borderColor = borderColor;
        }
    }
}

最近一直在看苹果公司提供的两本swift官方教程电子书,一部是《The Swift Programming Language》,另一部是《Using Swift With Cocoa and Objective-C》。昨天正好看到第二部电子书的“Writing Swift Classes with Objective-C Behavior”这一节,其中讲述了关于实时渲染这一技术。下面是摘抄的其中一段内容:

“Live Rendering
You can use two different attributes—@IBDesignable and @IBInspectable—to enable live, interactive custom view design in Interface Builder. When you create a custom view that inherits from the UIView class or the NSView class, you can add the @IBDesignable attribute just before the class declaration. After you add the custom view to Interface Builder (by setting the custom class of the view in the inspector pane), Interface Builder renders your view in the canvas. You can also add the @IBInspectable attribute to properties with types compatible with user defined runtime attributes. After you add your custom view to Interface Builder, you can edit these properties in the inspector. SWIFT @IBDesignable
class MyCustomView: UIView {
@IBInspectable var textColor: UIColor
@IBInspectable var iconHeight: CGFloat
/* ... */
}

其大意就是说,可以将自定义的代码实时渲染到Interface Builder中。而它们之间的桥梁就是通过两个指令来完成,即@IBDesignable和@IBInspectable。我们通过@IBDesignable告诉Interface Builder这个类可以实时渲染到界面中,但是这个类必须是UIView或者NSView的子类。通过@IBInspectable可以定义动态属性,即可在attribute inspector面板中可视化修改属性值。

话不多说,下面举一个简单的例子,这个例子自定义一个UIView的子类,该子类拥有一个UIButton。

import UIKit

@IBDesignable
class MyCustomView: UIView { @IBInspectable var buttonTitleColor: UIColor! // button title color
@IBInspectable var buttonTitle: String! // button title
@IBInspectable var buttonFrame: CGRect! // button frame var myButton: UIButton! override init(frame: CGRect) {
// init stored properties
buttonTitleColor = UIColor.redColor()
buttonTitle = "button title"
buttonFrame = CGRectMake(0, 0, 100, 50) myButton = UIButton(frame: buttonFrame)
myButton.setTitleColor(buttonTitleColor, forState: .Normal)
myButton.setTitle(buttonTitle, forState: .Normal) // call super initializer
super.init(frame: frame) // add button to self
addSubview(myButton) } required init(coder aDecoder: NSCoder) {
// init stored properties
buttonTitleColor = UIColor.redColor()
buttonTitle = "button title"
buttonFrame = CGRectMake(0, 0, 100, 50) myButton = UIButton(frame: buttonFrame)
myButton.setTitleColor(buttonTitleColor, forState: .Normal)
myButton.setTitle(buttonTitle, forState: .Normal) // call super initializer
super.init(coder: aDecoder) // add button to self
addSubview(myButton)
} override func layoutSubviews() {
// refresh button state through attribute inspector
myButton.setTitleColor(buttonTitleColor, forState: .Normal)
myButton.setTitle(buttonTitle, forState: .Normal)
} }

上图:

从图中可以看到,代码实时渲染到IB中了。

另外,我们在attribute inspector中也可以看到,由指令@IBInspectable声明的属性也出现在了面板中,通过修改这些值可以动态改变界面的效果(需要实现layoutSubviews方法)

具体工程一览:

Swift - @IBDesignable和@IBInspectable的更多相关文章

  1. swift 第十四课 可视化view: @IBDesignable 、@IBInspectable

    以前应objctiew-c 写项目的时候,就知道有这两个关键字,现在用swift了.用法稍作改变,基本用法还是一致的 虽然使用这个之后,有时候会报错的非常的莫名其妙----(其实还是自己技术不够牛…… ...

  2. @IBDesignable和@IBInspectable

    近期一直在看苹果公司提供的两本swift官方教程电子书,一部是<The Swift Programming Language>,还有一部是<Using Swift With Coco ...

  3. iOS @IBDesignable和@IBInspectable

    http://www.tuicool.com/articles/JVNRBjY @IBDesignable和@IBInspectable 时间 2014-10-08 11:02:03  CSDN博客 ...

  4. 在OC和Swift中使用IBDesignable/IBInspectable

    iOS8新特性IBDesignable/IBInspectable,可以直接在XIB或者Storyboard中直接,设置UI类的属性.例 如:UIView.layer.borderWidth.bord ...

  5. [翻译]使用Swift在Xcode中创建自定义控件

    使用Swift在Xcode中创建自定义控件 原文 IBDesignable and IBInspectable With IBDesignable and IBInspectable, develop ...

  6. ios Swift 特性

    特性提供了关于声明和类型的更多信息.在Swift中有两类特性,用于修饰声明的以及用于修饰类型的.例如,required特性,当应用于一个类的指定或便利初始化器声明时,表明它的每个子类都必须实现那个初始 ...

  7. 关于IB_DESIGNABLE / IBInspectable的那些事

    前言 IB_DESIGNABLE / IBInspectable 这两个关键字是在WWDC 2014年”What’s New in Interface Builder”这个Session里面,用Swi ...

  8. Swift互用性: 使用Objective-C特性编写Swift类(Swift 2.0版)-b

    本节包括内容: 继承Objective-C的类(Inheriting from Objective-C Classes) 采用协议(Adopting Protocols) 编写构造器和析构器(Writ ...

  9. swift 之xib自定义view可视化到storyboard

    首先直入正题:@IBInspectable & @IBDesignable 对于 @IBInspectable 和 @IBDesignable 可详见官方文档 : Creating a Cus ...

随机推荐

  1. utils部分--一些通用的工具类封装

    1.简介 utils部分是对一些常用的工具类进行简单的封装,使用起来比较方便.这里列举常用的一些. 2.ContextUtils使用 主要封装了网络判断.一些方法解释如下: ? 1 2 3 4 5 6 ...

  2. python 中的unicode详解

    通过例子来看问题是比较容易懂的. 首先来看,下面这个是我新建的一个txt文件,名字叫做ivan_utf8.txt,然后里面随便编辑了一些东西. 然后来用控制台打开这个文件,同样也是截图: 这里就是简单 ...

  3. word20161201

    http://baike.baidu.com/link?url=ZTTkA-suMlJNGb2AeNBE2E6MZQZwjkvWXKgmUpeLBIrCfC-k32cGJOJLrtDlLXjsTfkD ...

  4. OpenCV中对图像进行二值化的关键函数——cvThreshold()。

    函数功能:采用Canny方法对图像进行边缘检测 函数原型: void cvThreshold( const CvArr* src, CvArr* dst, double threshold, doub ...

  5. Python自动化之rabbitmq rpc client端代码分析(原创)

    RPC调用client端解析 import pika import uuid # 建立连接 class FibonacciRpcClient(object): def __init__(self): ...

  6. memcache的带图形界面监控工具memcachephp

    memcache也有一款图形界面的监控工具(memcachephp),可以通过这个工具查看到局域网内所有部署memcache机器或者端口的memcache的运行情况,对我们监控memcache的缓存命 ...

  7. 【转】.so兼容32位和64位

    本文转自:http://blog.csdn.net/fwt336/article/details/51700300 安卓的兼容性是一个很令人头疼的问题,这几天又遇到了,还好还是解决了. 我遇到的问题是 ...

  8. 64位win系统上面tomcat6启动不了 window不能再本地计算机启动

    64位的jdk装完之后,jre的bin目录下面没有client文件夹, 而tomcat6.0.20的默认配置启动在client文件夹下面. 所以打开tomcat6w,在java选项界面,取消Use d ...

  9. Dnsmasq安装与配置-搭建本地DNS服务器 更干净更快无广告DNS解析

    默认的情况下,我们平时上网用的本地DNS服务器都是使用电信或者联通的,但是这样也导致了不少的问题,首当其冲的就是上网时经常莫名地弹出广告,或者莫名的流量被消耗掉导致网速变慢.其次是部分网站域名不能正常 ...

  10. linux 解压缩

    tar f 使用档案名字,这个参数是最后一个参数,后面只能接档案名 c 建立压缩档案 x 解压 t 查看内容 r 向压缩归档文件末尾追加文件 u 更新原压缩包中的文件 z 有gzip属性的 j 有bz ...