UIButton 未激活

UIButton isn't active

我开始阅读 Aaron Hillegass 的一本书来学习 iOS 编程,但我发现有些示例不起作用。也许它们不起作用,因为有新版本的 iOS 和 Xcode。你能向我解释一下为什么这段代码不起作用吗?正在创建按钮;但是,它没有收到压力。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
     self.window.rootViewController = [[UIViewController alloc] init];
     button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     [button setFrame:CGRectMake(10,50,100,10)];
     [button setTitle:@"OK" forState:UIControlStateNormal];
     self.window.backgroundColor = [UIColor whiteColor];
     [self.window addSubview:button];
     [self.window makeKeyAndVisible];

     return YES;
}

关于此类问题的热门建议是添加

    button.userInteractionEnabled = YES;

但没用。

抱歉,如果我的问题很简单,但我花了几个小时在这里和 developer.apple.com 上找到答案。

尝试添加这些行

[button addTarget:self action:@selector(hello:) forControlEvents:UIControlEventTouchUpInside];

这是单击按钮时将调用的方法

- (void) hello:(id) sender
{


   NSLog(@"helloooo");
}

出于某种原因,按钮顶部有一个视图,它阻止按钮接收操作(按下)。您所要做的就是添加:

[self.window bringSubviewToFront:button];

这行代码会将您的按钮放在视图堆栈的顶部。干杯

首先你有 10 的高度,这非常小。可能你没打中

您可以在 AppDelegate 中执行此操作,但您通常希望使用 ViewController。如果您是 iOS 开发的新手,您肯定不希望在 AppDelegate 中有任何这些。 我建议在 ViewController 中完成所有这些操作,因为它覆盖在 UIWindow.

之上

此外,您必须添加@rahul-patel 来测试它是否启用。

更新: 我完全同意其他答案。所有这些 must/should 都完成了。添加@rahul-patel 和@matthew-s 的内容