在Swift中UIButton添加点击事件的最大区别在selector.
下面直接看代码:
// // ViewController.swift // 1.UILabel // // Created by zhuming on 16/1/24. // copyright © 2016年 zhuming. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label1: UILabel! var coun = 0 override func viewDidLoad() { super.viewDidLoad() label1.text = "第一个Label标签" creatLabel2() creatButton() // Do any additional setup after loading the view,typically from a nib. } /** 创建一个标签对象 */ func creatLabel2(){ // 初始化一个label2对象 并设置frame值 let label2 = UILabel(frame: CGRect(x: 20,y: 200,width: 200,height: 80)) label2.text = "第二个Label标签2e3gr35hjym eRGBHRTN HRGBHTN H" // 标签显示内容 label2.textAlignment = NSTextAlignment.Center //对齐方式 label2.textColor = UIColor.greenColor() // 字体颜色 label2.font = UIFont.systemFontOfSize(12) // 字体大小 label2.backgroundColor = UIColor.grayColor() // 背景颜色 label2.shadowColor = UIColor.redColor() // 阴影颜色 label2.shadowOffset = CGSizeMake(10,10) // 阴影偏移量 label2.numberOfLines = 0 // 0:多行显示 label2.adjustsFontSizetoFitWidth = true //根据标签长度自动调整字体大小 需要注释掉多行显示才有效果 // 下面这两个属性 打开字体高亮 和设置字体高亮颜色 会覆盖原来设置的字体颜色 label2.highlightedTextColor = UIColor.whiteColor() label2.highlighted = true self.view .addSubview(label2) } func creatButton(){ let button = UIButton(frame: CGRect(x: 50,y: 300,width: 100,height: 40)) button.setTitle("按钮",forState: UIControlState.normal) button.backgroundColor = UIColor.redColor() button .addTarget(self,action: Selector("btnClick"),forControlEvents: UIControlEvents.TouchUpInside) /* // OC 里面UIButton添加点击事件 [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside]; self.view .addSubview(button) */ } func btnClick(){ // 按钮点击事件 print("按钮按下") coun = coun + 1; label1.text = "\(coun)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // dispose of any resources that can be recreated. } }效果图:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。