Label
enum VLabelTextModel {
case Top
case Center
case Bottom
}
class VLabel: UIView {
let label = UILabel()
//计算属性
var text: String! {
set {
self.label.text = newValue
}
get {
return self.label.text
}
}
var verticalModel: VLabelTextModel = .Top
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addSubview(label)
}
override func layoutSubviews() {
super.layoutSubviews()
//计算文字所需要占据的区域
var rect = label.textRectForBounds(self.bounds, limitedToNumberOfLines: 0)
switch verticalModel {
case .Top:
break
case .Center:
rect.origin.y = self.bounds.size.height / 2 - rect.size.height / 2
case .Bottom:
rect.origin.y = self.bounds.size.height - rect.size.height
}
label.frame = rect
}
}
ProgressView
class ProgressView: UIView {
private var p: CGFloat = 0
var progress: CGFloat {
set {
if newValue < 0 {
p = 0
}
else if newValue > 1 {
p = 1
}
else {
p = newValue
}
self.setNeedsLayout() //让系统调用layoutSubviews
}
get {
return p
}
}
var trackView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(trackView)
setColors()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addSubview(trackView)
setColors()
}
func setColors() {
self.backgroundColor = UIColor.blueColor()
trackView.backgroundColor = UIColor.redColor()
}
//不应该直接调用
override func layoutSubviews() {
super.layoutSubviews()
trackView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width * progress, height: self.frame.size.height)
}
}