今回はアプリにボタンを実装する過程で
UIButtonを使う度にボタンを角丸にするのがバカらしいと思ってので、サブクラスを作ることにしました。
コードは以下のようになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import UIKit class RoundedButton: UIButton { init(frame: CGRect, label: String, backgroundColor: UIColor, titleColor: UIColor) { super.init(frame: frame) self.setTitle(label, for: .normal) self.layer.cornerRadius = 2.0 self.backgroundColor = backgroundColor self.setTitleColor(titleColor, for: .normal) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } |
UIButtonを継承して、クラス名をRoundedButtonとしました。
インスタンスを生成する際にイニシャライザに、
Buttonのサイズを決めるframe、ボタンの文字のlabel、色を決めるbackgroundColor, 文字の色を決めるtitleColorを渡しています。
実際に使う際は、
ViewController内のviewDidLoad()で以下のように使います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
override func viewDidLoad() { super.viewDidLoad() // ボタン let bin = RoundedButton( frame : CGRect(x: 0,y: 0,width: self.view.bounds.width*0.9 ,height: 45), label : "ボタン", backgroundColor: UIColor.init(red: 239/255, green: 83/255, blue: 80/255, alpha: 100/100), titleColor : UIColor.white ) // ボタンの位置 btn.layer.position = CGPoint( x: self.view.bounds.width / 2, y: self.view.bounds.height - btn.bounds.height / 2 - DeviceSize.tabBarHeight(tabBarController: UITabBarController()).height - 10 ) btn.addTarget(self, action: #selector(ViewController.startBtn(sender:)), for: .touchUpInside) self.view.addSubview(startBtn) } @objc fund startBtn() { // ボタンが押された時の処理 } |
このように、
頻繁に使うようなUIは、サブクラスを定義してあげて
ViewController内で面倒なことを省けるようにしてあげれば開発効率もだるさも減るのでオススメですよ!