【www.bbyears.com--php常用代码】
通常在开发中,为了使代码更加简洁,我们常常会把常用的功能封装成一个个组件(或者称UI元件、UI控件),同时这样也更利于代码的复用。
我原来写过一篇文章,介绍如何通过继承UIView来实现自定义组件:Swift - 继承UIView实现自定义可视化组件(附记分牌样例)
本文介绍如何在StoryBoard中使用自定义组件,有如下优势:
(1)在StoryBoard中我们就可以很方便地调整自定义组件的位置、布局以及相关约束。
(2)可以在属性面板设置自定义组件的各个属性(包括自定义属性),同时StoryBoard的视图区域中也会实时地将样式体现出来。
1,自定义可视化组件的创建
这里以自定义一个简单的进度条组件为例,用户可以自由设置进度条的进度、尺寸、文字颜色、进度条颜色、背景颜色。
原文:Swift - 在StoryBoard中添加使用自定义组件(自定义进度条组件为例)
自定义组件的关键是使用如下两个Interface Builder(下文用IB简称)属性声明:IBInspectable和IBDesignable。
@IBDesignable:用来标识自定义组件类,这样在StoryBoard中就能能实时更新视图。
@IBInspectable:用来标识属性,这样在Attribute Inspector(属性检查器)中查看设置该属性。
import UIKit
@IBDesignable class MyProgressBar: UIView {
//显示进度的文本标签
private let textLabel = UILabel()
//显示当前进度区域
private let bar = UIView()
//进度
@IBInspectable var percent: Int = 0 {
didSet {
if percent > 100 {
percent = 100
}else if percent < 0 {
percent = 0
}
textLabel.text = "\(percent)%"
setNeedsLayout()
}
}
//文本颜色
@IBInspectable var color: UIColor = .whiteColor() {
didSet {
textLabel.textColor = color
}
}
//进度条颜色
@IBInspectable var barColor: UIColor = UIColor.orangeColor() {
didSet {
bar.backgroundColor = barColor
}
}
//进度条背景颜色
@IBInspectable var barBgColor: UIColor = UIColor.lightGrayColor() {
didSet {
layer.backgroundColor = barBgColor.CGColor
}
}
//init方法
override init(frame: CGRect) {
super.init(frame: frame)
initialSetup()
}
//init方法
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
//页面初始化相关设置
private func initialSetup() -> Void {
bar.backgroundColor = self.barColor
addSubview(bar)
textLabel.textAlignment = .Center
textLabel.numberOfLines = 0
textLabel.textColor = self.color
textLabel.text = "\(self.percent)%"
addSubview(textLabel)
}
//布局相关设置
override func layoutSubviews() {
super.layoutSubviews()
layer.backgroundColor = self.barBgColor.CGColor
var barFrame = bounds
barFrame.size.width *= (CGFloat(self.percent) / 100)
bar.frame = barFrame
textLabel.frame = bounds
}
}
可以先使用代码测试下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myProgressBar = MyProgressBar(frame: CGRectMake(50, 50, 200, 20))
myProgressBar.percent = 50
self.view.addSubview(myProgressBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
(1)打开Main.storyboard,从组件库里添加一个视图(View)
(2)在Identity Inspector里把视图类改成MyProgressBar
(3)可以看到自定义组件已经渲染显示出来了
(4)在Attributes inspector面板中可以调整组件的各个自定义属性
(注:如果自定义组件是没有使用IB关键字,也是可以在StoryBoard中添加使用的。只不过在StoryBoard中不能实时更新视图和属性,显示的是一个空白矩形。)