コードで、各UIを設定している時に
CustomView.swift
class CustomView: UIView {
var hogeButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
hogeButton.setTitle("登録", forState: .Normal)
hogeButton.tintColor = UIColor.whiteColor()
hogeButton.backgroundColor = UIColor.blueColor()
hogeButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -40, bottom: 0, right: 40)
hogeButton.titleLabel!.font = UIFont(name:"HelveticaNeue-Bold",size:17)
hogeButton.layer.cornerRadius = 3.0
addSubview(hogeButton)
}
override func layoutSubviews() {
super.layoutSubviews()
let maxX = self.frame.width
let maxY = self.frame.height
hogeButton.frame = CGRectMake(5, maxY+10, maxX/2, 40)
}
メソッドチェインでプロパティの設定とか書けたら、もっとまとまりがあって便利なんじゃないかと思いました。
とりあえず、Extensionでこんな感じに作ってみました。
UIButton+methodChain.swift
extension UIButton {
func mc_setTitle(title: String, state: UIControlState) -> UIButton {
self.setTitle(title, forState: state)
return self
}
func mc_setTitleColor(titleColor: UIColor, state: UIControlState) -> UIButton {
self.setTitleColor(titleColor, forState: state)
return self
}
func mc_setImage(image: UIImage, state: UIControlState) -> UIButton {
self.setImage(image, forState: state)
return self
}
func mc_setBorder(borderColor: UIColor, borderWidth: CGFloat) -> UIButton {
self.layer.borderColor = borderColor.CGColor
self.layer.borderWidth = borderWidth
return self
}
func mc_setBackgroundColor(color: UIColor) -> UIButton {
self.backgroundColor = color
return self
}
}
で、使ってみたらこんな感じに
CustomView.swift
class CustomView: UIView {
var hogeButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
hogeButton.mc_setTitle("ほげほげ", state: .Normal)
.mc_setTitleColor(UIColor.blackColor(), state: .Normal)
.mc_setImage(UIImage(named: "close")!, state: .Normal)
.mc_setBackgroundColor(UIColor.redColor())
.mc_setBorder(UIColor.whiteColor(), borderWidth: 2.0)
addSubview(hogeButton)
}
override func layoutSubviews() {
super.layoutSubviews()
let maxX = self.frame.width
let maxY = self.frame.height
hogeButton.frame = CGRectMake(0, 0, 200, 60)
hogeButton.center = CGPoint(x: maxX/2, y: maxY/2)
}
うーん?まとまった?
途中で、Extensionを各UI分作る気力が起きず、妥協しました。
もっとよりよい方法があったら、ご教授お願い致します。