在程序代码中设定控件调用的方法
在程序代码中设定控件调用的方法
?
一般情况下,我们都是通过在XIB界面中添加控件,然后在程序中编写控件方法,最后通过XIB将控件和方法进行绑定。
?
本文,将介绍如何直接在程序中将编写的方法与控件进行绑定。
?
这里的例子将继续文章《通过Window-based Application创建项目(一)》中的示例!
?
操作很简单,参考下面代码中的红色部分。
?
?
FirstViewController.h 修改:
?
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
UILabel *label;
UIButton *button;
}
@property (nonatomic,retain) UILabel *label;
@property (nonatomic,retain) UIButton *button;
-(IBAction)myButtonClicked:(id)sender;
@end
?
?
?
FirstViewController.m 修改:
?
#import "FirstViewController.h"
@implementation FirstViewController
@synthesize label,button;
-(IBAction)myButtonClicked:(id)sender{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"my alert"
? message:@"button is clicked"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
[alert show];
[alert release];
}
// The designated initializer.? Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
??? self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
??? if (self) {
??????? // Custom initialization.
??? }
??? return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
//create the label
CGRect frame=CGRectMake(50, 30, 200, 45);
label=[[UILabel alloc] initWithFrame:frame];
label.text=@"This is a label";
//create the button
frame=CGRectMake(50, 100, 200, 45);
button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=frame;
[button setTitle:@"OK" forState:UIControlStateNormal];
[button addTarget:self
? action:@selector(myButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];
//add the label and button into current view.
[self.view addSubview:label];
[self.view addSubview:button];
??? [super viewDidLoad];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
??? // Return YES for supported orientations.
??? return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
??? // Releases the view if it doesn't have a superview.
??? [super didReceiveMemoryWarning];
??? // Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
??? [super viewDidUnload];
??? // Release any retained subviews of the main view.
??? // e.g. self.myOutlet = nil;
}
- (void)dealloc {
[label release];
[button release];
??? [super dealloc];
}
@end
?
?
运行后,点击界面上的【OK】按钮,即显示效果如下图:
?
?
?
?
关于控件对应方法在系统中的常量定义如下表:
All events, including system events.
Available in iOS 2.0 and later.
Declared in?UIControl.h
.
?
?