swift button点击事件

//
//  ViewController.swift
// 按钮
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // ❗️SWIFT 提倡:
        // Replace 'Selector("buttonTap")' with '#selector(ViewController.buttonTap)'

        // button  点击无参数
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
        button.backgroundColor = UIColor.yellow
        button.addTarget(self, action: #selector(ViewController.buttonTap), for: UIControlEvents.touchUpInside)
        //button1:点击有参数
        let button1 = UIButton(frame: CGRect(x: 100, y: 0, width: 50, height: 30))
        button1.backgroundColor = UIColor.yellow
        button1.addTarget(self, action: #selector(buttonTap1(button:)), for: UIControlEvents.touchUpInside)

        self.view.addSubview(button)
        self.view.addSubview(button1)
    }

    //selector 其实是 Objective-C runtime 的概念
    @objc func buttonTap() {
        print("buttonTap")
    }

    @objc func buttonTap1(button:UIButton) {
        print("buttonTap参数")
    }




}

你可能感兴趣的:(SWIFT基础知识)