输入!按键 UIButton
UIButton 负责与触控事件做互动,将按下结果透过事件方式产生,它继承了UIControl并提供设定标题文字、外观…等,以下用程式方式产生UIButton需要的功能。
执行结果
Log
onClickButton 事件 Tag:1
Swift 程式范例
//-----------start----------- // // ViewController.swift // // import UIKit class ViewController: UIViewController { let dyButton: UIButton = UIButton() override func viewDidLoad() { super.viewDidLoad() // 初始化 dyButton.frame = CGRectMake(0,0,200,40) // 设定背景颜色 dyButton.backgroundColor = UIColor.brownColor() // 遮罩功能是否开启 dyButton.layer.masksToBounds = true // 遮罩功能开启后指定圆角大小 dyButton.layer.cornerRadius = 10.0 //设定正常状态下显示的文字 dyButton.setTitle("正常", forState: UIControlState.Normal) //设定正常状态下文字的颜色 dyButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) //设定按下状态下显示的文字 dyButton.setTitle("按下", forState: UIControlState.Highlighted) //设定按下状态下文字的颜色 dyButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Highlighted) // layer座标指定,init Button时会将Layer座标设定与frame相同 dyButton.layer.position = CGPoint(x: self.view.frame.width/2, y:100) //设定tag dyButton.tag = 1 //增加Click事件回呼,TouchUpInside 意指手指按下后离开产生的事件 dyButton.addTarget(self, action: "onClickButton:", forControlEvents: .TouchUpInside) // 将设定好的Button加入原本的view self.view.addSubview(dyButton) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //Button按下按键后会执行此function func onClickButton(sender: UIButton){ println("onClickButton 事件") println("Tag:\(sender.tag)") } } //------------end------------
Objective-C 程式范例
//-----------start----------- // // ViewController.m // // // #import "ViewController.h" #import <UIKit/UIKit.h> @interface ViewController () @end @implementation ViewController { UIButton *dyButton; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 初始化 dyButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; dyButton.backgroundColor = [UIColor brownColor]; dyButton.layer.masksToBounds = TRUE; dyButton.layer.cornerRadius = 10.0; [dyButton setTitle:@"正常" forState: UIControlStateNormal]; [dyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [dyButton setTitle:@"按下" forState: UIControlStateHighlighted]; [dyButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; dyButton.layer.position = CGPointMake(self.view.frame.size.width/2, 100); dyButton.tag = 1; [dyButton addTarget:self action:@selector(onClickButton:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:dyButton]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)onClickButton:(id)sender { NSLog(@"onClickButton 事件"); NSLog(@"Tag:\(sender.tag)"); } @end //------------end------------