定制XCode的UI控件

有时候我们需要一些深度定制的并且多次多次复用的UI控件,为了模块化程序,在iOS8 及以后,我们可以将常用的定制UI控件放到自己的Kit里面,在不同的项目中重复使用。

本文主要记录怎样定制UI控件

 

 

主要的参考文档在这里:Creating a Custom View That Renders in Interface Builder

 

首先我们要在build target中添加cocoa touch framework。完成后,我们就开始往里面添加我们定制的class。通常情况下,我们一般都是subclass UIView,有时候省功夫,可以subclass UIButton。

在Class的开头处,添加 @IBDesignable

import UIKit

@IBDesignable

public class kkIndicator: UIButton {

//........

}

这样Interface Builder就会实时编译你对这个class的修改。

 

 

对于一些需要出现在Interface Builder里面的可调参数,可以在变量前面添加@IBInspectable,另外可以添加默认的初始值。内部可以添加didSet willSet观察值的变化,及时对组件作出更新操作。

@IBInspectable public var rotateDuration : CGFloat = 1.0 {
	didSet {
		animation.duration = CFTimeInterval(rotateDuration)
	}
}

 

遗憾的是,这个值只能够支持非常有限的变量,不能支持enum等类型,不过还是够用的吧。

 

You can attach the IBInspectable attribute to any property in a class declaration, class extension, or category for any type that’s supported by the Interface Builder defined runtime attributes: boolean, integer or floating point number, string, localized string, rectangle, point, size, color, range, and nil.

苹果原文

 

对于UIView的subclass,我们需要考虑怎样从decoder里面弄出来(其实所有的控件都要考虑怎么弄吧)

override public init(frame: CGRect) {
	super.init(frame: frame)
	configure()
}
	
required public init?(coder aDecoder: NSCoder) {
	super.init(coder: aDecoder)
	configure()
}
	
private func configure() {

}

 

你会发现Interface Builder是从

required public init?(coder aDecoder: NSCoder) {}

然而正常的运行时候是从

override public init(frame: CGRect) {}

触发的。

这篇博文发表在 应用开发 | App Dev 目录下,标签为 , , ,
如需引用,请使用链接:https://note.mc256.dev/?p=1158

This article published in 应用开发 | App Dev with tags , , , .
Cite this page using this link:https://note.mc256.dev/?p=1158

您的邮箱地址不会被公开,评论使用Gravatar头像。
Your email address will not be published. This blog is using Gravatar.

正在提交评论... Submitting ...
正在为您准备评论控件 Loading Comment Plugin
Copyright © 2013-2023 mc256. All Rights Reserved.
Powered by WordPress on top of a dual-stack k3s Cluster using JuiceFS.
Wordpress Theme Designed By mc256.
Encrypted By Let's Encrypt.  Hosted On Linode + OVH + AWS.
DNS Provided By Hostker.
Status Page by CloudFlare Worker.