swift4.0 方法監聽Selector寫法總結

ZY_FlyWay發表於2018-02-02

import UIKit

class MainViewController: UITabBarController {
    
    //MARK:屬性 懶載入
    lazy var composeBtn = UIButton(composeForeImageName: "tabbar_compose_icon_add", composeBackImageName: "tabbar_compose_button")

    
    //MARK:重寫方法
    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.addSubview(composeBtn)
    }
    
    override func viewWillLayoutSubviews() {
        composeBtn.center = CGPoint(x: tabBar.center.x, y:tabBar.bounds.height * 0.5)
        
        //方法1:Selector("方法名")  Swift已經不推薦使用,會被提示改成第二種代替
//        composeBtn.addTarget(self, action:Selector(("composeBtnClick")), for: .touchUpInside)
        //方法2:Selector("類名.方法名") 推薦寫法
        composeBtn.addTarget(self, action:#selector(MainViewController.composeBtnClick), for: .touchUpInside)
        //方法3:"方法名"
//          composeBtn.addTarget(self, action:"composeBtnClick", for: .touchUpInside)

    }

}

//MARK:事件監聽
extension MainViewController{
    
    //這裡必須要加@objc 否則會崩潰
    @objc func composeBtnClick(){
        print("composeBtnClick")
    }
}





相關文章