LoginSignup
0
2

More than 5 years have passed since last update.

UIとロジックをクラスで分離する - iOS

Posted at

UIButtonのロジックの実装

ViewController.swift

/*

UIButtonのロジックの実装

*/

var sHeight:CGFloat?
var sWidth:CGFloat?

class ViewController: UIViewController {


    @objc func doButtonActioin(sender: Any) {
        print("ボタンが押された時の処理")
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        sHeight = self.view.frame.width/2
        sWidth = self.view.frame.height/2

        //ボタンを画面に描画
        self.view.addSubview(myButton().myButtonFunc())

UIButtonのUIの実装

ButtonUI.swift

/*

UIButtonのUIの実装

*/

class myButton: UIButton {

    func myButtonFunc() -> UIButton {

        let myButton = UIButton()

        myButton.frame = myButtonView().myButtonViewFunc()
        myButton.backgroundColor = UIColor.cyan
        myButton.setTitle("tap me", for: .normal)
        myButton.addTarget(self, action: #selector(ViewController().doButtonActioin(sender: )), for: .touchUpInside)
        // buttonにイベントを追加
        return myButton
    }
}

UIButtonのレイアウトの実装

ButtonLayout.swift

/*

UIButtonのレイアウトの実装 

*/

class myButtonView: UIView {

    func myButtonViewFunc() -> CGRect{

        let rectx =  sWidth!/2
        let recty = sHeight!/2
        let rectWidth = sWidth!/2
        let rectHeight = sHeight!/2
        let buttonRect = CGRect(x:rectx,y:recty,width:rectWidth,height:rectHeight)

        return buttonRect
    }
}
0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2