1、问题描述:从
Viewcontroller.m中创建一个红色的Button.运行后点击button不会执行button tap事件。
AppDelegate.m创建app窗口,定义rootviewcontroller时,在rootviewcontroller创建按钮,不响应事件动作
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//UIWindow -> UIView -> RootViewController
//****UIWindow
//从代码里面创建第一个窗口window
self.window = [[UIWindow alloc]init];
//设置窗口的fram color
self.window.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height);
//还可以选择行改变顶上面导航栏的样式
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
self.window.backgroundColor = [UIColor clearColor];
self.window.backgroundColor = [UIColor whiteColor];
//设置rootviewcontroller
ViewController *firstviewcontrol = [[ViewController alloc]init];
[self.window setRootViewController:firstviewcontrol];
UIView *rview = [[UIView alloc]initWithFrame:self.window.frame];
[self.window addSubview:rview];
rview.backgroundColor=[UIColor redColor];
[self.window addSubview:rview];
[self.window makeKeyAndVisible];
}
Viewcontroller.m中创建一个红色的Button.运行后点击button不会执行button tap事件。
UIButton *testbutton = [UIButton buttonWithType:UIButtonTypeCustom];
testbutton.frame = CGRectMake(50, 300, 100, 100);
[testbutton setTitle:@"创建一个按钮" forState:UIControlStateNormal];
//testbutton.backgroundColor = [UIColor clearColor];
testbutton.backgroundColor = [UIColor redColor];
[testbutton addTarget:self action:@selector(buttontap) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:testbutton];
视图叠加的顺序和代码执行的顺序一致:UIwindow -> rootviewcontroller +(rootviewcontroller中的subview) -> rview
一般最好不要在AppDelegate.m中再加在其他UIview,最好都在各自的viewcontroller中创建UIView.如果非要创建注意叠加的顺序,或者在进入主控制器时remove这个view
修改成这个样子:
self.window = [[UIWindow alloc]init];
//设置窗口的fram color
self.window.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height);
//还可以选择行改变顶上面导航栏的样式
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
self.window.backgroundColor = [UIColor clearColor];
self.window.backgroundColor = [UIColor whiteColor];
<span style="color:#ff0000;"> UIView *rview = [[UIView alloc]initWithFrame:self.window.frame];
[self.window addSubview:rview];
//rview.backgroundColor=[UIColor redColor];
[self.window addSubview:rview];
//设置rootviewcontroller</span>
ViewController *firstviewcontrol = [[ViewController alloc]init];
[self.window setRootViewController:firstviewcontrol];
[self.window makeKeyAndVisible];