輸入!按鍵 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------------