Swift4.0 - 设置 UIButton的点击方法

Swift越来越成熟,按钮的点击方法和OC的还有些差别的。代码如下:

class HomeViewController: BaseViewController {

    //懒加载一个按钮 loginDidSelected可以换成你写方法名
    lazy var loginButton: UIButton = {
        
        let loginButton = UIButton.init(type: .custom)
        loginButton.setTitle("登录", for: .normal)
        loginButton.backgroundColor = UIColor.red;
        loginButton.addTarget(self, action: #selector(loginDidSelected), for: .touchUpInside)
        
        return loginButton
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //引入方法
        self.createSubView()
    }
    
    func createSubView() {
        
        self.view.addSubview(self.loginButton)
        
    }
    //用SnapKit(OC的Masonry)给按钮设置约束
    override func viewDidLayoutSubviews() {
        
        self.loginButton.snp.makeConstraints { (make) in
            
            make.left.equalTo(self.view.snp_leftMargin).offset(30)
            make.top.equalTo(self.view.snp_topMargin).offset(100)
            make.width.equalTo(100)
            make.height.equalTo(60)
            
        }
        
    }
    
    //设置按钮的点击方法
    @objc func loginDidSelected() {
        
        BJDLog("您点击的登录按钮");
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

代码仅供参考,大家共同学习

你可能感兴趣的:(Swift4.0 - 设置 UIButton的点击方法)