1 前言
UIButton為按鈕控件,在IOS開發中十分常見,可以為其設置事件。
2 代碼實例
ZYViewController.m:
@synthesize myButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];//設置按鈕樣式為圓角矩形
myButton.frame = CGRectMake(110.0f, 200.0f, 100.0f, 37.0f);
[myButton setTitle:@"Press Me" forState:UIControlStateNormal];//按下按鈕時候的標題
[myButton setTitle:@"I'm Pressed" forState:UIControlStateHighlighted];//按下按鈕後抬手時候的標題
[myButton addTarget:self action:@selector(buttonIsPressed:) forControlEvents:UIControlEventTouchDown];//按下按鈕觸發事件
[myButton addTarget:self action:@selector(buttonIsTapped:) forControlEvents:UIControlEventTouchUpInside];//按下按鈕後抬手時候觸發事件
[self.view addSubview:myButton];
}
-(void)buttonIsPressed:(UIButton *)paramSender{
NSLog(@"Button is pressed");
}
-(void)buttonIsTapped:(UIButton *)paramSender{
NSLog(@"Button is tapped");
}
@synthesize myButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];//設置按鈕樣式為圓角矩形
myButton.frame = CGRectMake(110.0f, 200.0f, 100.0f, 37.0f);
[myButton setTitle:@"Press Me" forState:UIControlStateNormal];//按下按鈕時候的標題
[myButton setTitle:@"I'm Pressed" forState:UIControlStateHighlighted];//按下按鈕後抬手時候的標題
[myButton addTarget:self action:@selector(buttonIsPressed:) forControlEvents:UIControlEventTouchDown];//按下按鈕觸發事件
[myButton addTarget:self action:@selector(buttonIsTapped:) forControlEvents:UIControlEventTouchUpInside];//按下按鈕後抬手時候觸發事件
[self.view addSubview:myButton];
}
-(void)buttonIsPressed:(UIButton *)paramSender{
NSLog(@"Button is pressed");
}
-(void)buttonIsTapped:(UIButton *)paramSender{
NSLog(@"Button is tapped");
}
運行結果:
點擊按鈕時候: