行书三大家:Ipad开发课程-Charpter4 创建和链接Actions ? 疯狂的老九
来源:百度文库 编辑:九乡新闻网 时间:2024/05/06 05:44:47
Ipad开发课程-Charpter4 创建和链接Actions
7Sep
Posted by: 9 in: Iphone程序开发
听课一周了,要努力加油啊....
在前面的例子中,你看到了怎么样添加一个Label和一个Button视图到主视图窗口.不管怎样,你需要去控制好Button视图,以至于当用户按下按钮时,它要有所显示.在Charpter3中,我们接触过outlets和actions,已经我们怎么样用代码将他们和InterfaceBuilder链接,接下来我们应该尝试视图直接用代码来创建,因此我们不需要用到InterfaceBuilder去连接actions和outlets.必须的,没有理由.
试试吧:例子,Linking Actions to Views
1.继续用到我们上节的windowBasedApp项目,在MySecondviewcontroller.h文件中声明这个buttonClicked:action
#import
#import
@interface MySecondViewController : UIViewController {
//---create two outlets - label and button---
UILabel *label;
UIButton *button;
}
//---expose the outlets as properties---
@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UIButton *button;
//---declaring the IBAction---
-(IBAction) buttonClicked: (id) sender;
@end
2.在MySecondViewController.m文件中,你定义按钮触发时的响应buttonClicked:action:
-(IBAction) buttonClicked: (id) sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@“Action invoked!”
message:@“Button clicked!”
delegate:self
cancelButtonTitle:@“OK”
otherButtonTitles:nil];
[alert show];
[alert release];
}
3.将buttonClicked:action和链接按钮视图的相关事件链接,会用到viewDidLoad()方法:
- (void)viewDidLoad {
//---create a CGRect for the positioning---
CGRect frame = CGRectMake(10, 10, 300, 50);
//---create a Label view---
label = [[UILabel alloc] initWithFrame:frame];
label.textAlignment = UITextAlignmentCenter;
label.font = [UIFont fontWithName:@“Verdana” size:20];
label.text = @“This is a label”;
//---create a Button view---
frame = CGRectMake(10, 250, 300, 50);
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@“OK” forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
//---add the action handler and set current class as target---
[button addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
//---add the views to the current View---
[self.view addSubview:label];
[self.view addSubview:button];
[super viewDidLoad];
}
4.试试吧,C+R..你可以看到这个结果了:
这里有一些常用的控制事件:
UIControlEventTouchDown
UIControlEventTouchDownRepeat
UIControlEventTouchDragInside
UIControlEventTouchDragOutside
UIControlEventTouchDragEnter
UIControlEventTouchDragExit
UIControlEventTouchUpInside
UIControlEventTouchUpOutside
UIControlEventTouchCancel
UIControlEventValueChanged
UIControlEventEditingDidBegin
UIControlEventEditingChanged
UIControlEventEditingDidEnd
UIControlEventEditingDidEndOnExit
UIControlEventAllTouchEvents
UIControlEventAllEditingEvents
UIControlEventApplicationReserved
UIControlEventSystemReserved
UIControlEventAllEvents
要了解这些事件的细节可以浏览:http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIControl_Cl
ass/Reference/Reference.html#//apple_ref/doc/constant_group/Control_Events.