iOS开发基础[swift] - UI控件 - 为按钮添加触发事件

这篇博客介绍了在iOS开发中使用Swift为UI按钮添加触发事件的基础知识,包括如何设置按钮的点击事件,以实现特定的功能或交互。通过学习,开发者可以理解并掌握在Swift项目中为按钮配置事件响应的方法。
摘要由CSDN通过智能技术生成

为按钮添加触发事件

import UIKit


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel(frame: CGRect(x: 120,y: 120,width: 200,height: 30))
        label.text = "我是一个便签控件"
        self.view.addSubview(label)//把label添加到当前视图
        let button = UIButton(type: UIButtonType.system)
        button.frame = CGRect(x: 220,y: 240,width: 100,height: 30)
        button.setTitle("按钮", for: UIControlState())
        button.backgroundColor = UIColor.purple
        self.view.addSubview(button)//把button添加到当前视图
        button.addTarget(self,action: #selector(touchBegin),for:UIControlEvents.touchUpInside)//一个设计好了的,可以监听到用户的点击事件的函数
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    func touchBegin() {
        print("用户点击了按钮")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

运行结果

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值