首先我们需要了解MVC模式(Model-View-Controller)。也许有些人和我一样,以前学过WEB开发。
所以对MVC比较了解。但是真正运用开发时只知道其中的实现。对于具体的理论我就不做过多的介绍。
效果如图所示:
当我们点击onClick按钮时会改变上面Label的内容。
代码如下:
首先在TestAlertViewController 中声明两个变量。也就是button和label;
然后在声明一个方法,是点击按钮时触发事件所要处理的方法
#import "MyAlertView.h" #import <UIKit/UIKit.h> @interface TestAlertViewController : UIViewController { UIButton *myButton; UILabel *myLabel; } @property (nonatomic, retain) UIButton *myButton; @property (nonatomic, retain) UILabel *myLabel; -(IBAction) buttonPress:(id)sender; @end
在TestAlertViewController 实例化两个变量。并完成处理事件的方法。
-(IBAction) buttonPress:(id)sender { myLabel.text = @"onClick myButton!"; }
- (void)viewDidLoad { myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; myButton.frame = CGRectMake(120, 220, 80, 40); [myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitle:@"onClick" forState:UIControlStateNormal]; [myButton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];//添加myButton处理事件的方法。[self.view addSubview:myButton]; myLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 50, 140, 40)]; myLabel.textAlignment = UITextAlignmentCenter; myLabel.text = @"HelloWorld"; [self.view addSubview:myLabel]; [super viewDidLoad]; }
- (void)viewDidLoad { myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; myButton.frame = CGRectMake(120, 220, 80, 40); [myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitle:@"onClick" forState:UIControlStateNormal]; [myButton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:myButton]; myLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 50, 140, 40)]; myLabel.textAlignment = UITextAlignmentCenter; myLabel.text = @"HelloWorld"; [self.view addSubview:myLabel]; [super viewDidLoad]; }
- (void)viewDidLoad { myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; myButton.frame = CGRectMake(120, 220, 80, 40); [myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitle:@"onClick" forState:UIControlStateNormal]; [myButton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:myButton]; myLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 50, 140, 40)]; myLabel.textAlignment = UITextAlignmentCenter; myLabel.text = @"HelloWorld"; [self.view addSubview:myLabel]; [super viewDidLoad]; }