删掉原来自用的ViewCotroller,新建一个TestViewController
在对应的AppDelegate中didFinishLaunchingWithOptions函数下,加入创建TestViewController视图的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
TestViewController *testController = [[TestViewController alloc] init];
self.window.rootViewController = testController;
[testController release];
return YES;
}
这时候View被创建出来了,要想在View上面加入Button,需要在viewDidLoad函数中加入如下创建Button的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(20, 20, 280, 40);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:@"点击" forState:UIControlStateNormal];
[btn addTarget:self
action:@selector(testOut:)
forControlEvents:UIControlEventTouchUpInside
];
[self.view addSubview:btn];
}
testOut函数:
声明(.h中):
- (IBAction)testOut:(UIButton *)sender;
定义(.m中):
- (IBAction)testOut:(UIButton *)sender
{
NSLog(@"testOut Event");
}
这样写了之后,就可以看到下面的效果:
同样的,这只是简单的代码,如果想要为这个Button的样式做一些调整,还有这样的属性设置:
[btn setImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal];
等等……