ios - 以编程方式将 UIButton 添加到 UINavigationBar 的 subview 并且触摸事件未注册

标签 ios objective-c xcode uibutton

我在 UINavigationController 中有一个 UITableView。为了在屏幕底部制作一个不随表格单元格移动的工具栏,我添加了一个 UIView 作为导航栏的 subview 。

然后我以编程方式创建一个 UIButton 来添加这个 UIView。我添加了一个选择器,但它没有注册并调用了我将其设置为 (sendMessage) 的函数。

self.sendBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-100, self.view.frame.size.width,100 )];
self.sendBar.backgroundColor = cloudBlue;
UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,50,50)];
sendButton.backgroundColor = [UIColor blackColor];
[sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
[self.navigationController.navigationBar addSubview:self.sendBar];
[self.sendBar addSubview:sendButton];

最佳答案

我怀疑这可能与您将按钮添加为“sendBar”的 subview 但从主视图引用选择器这一事实有关。您可以在这里做两件事:

1:将您的 sendBar 创建为 UIView 的自定义子类,其中包括您的 sendButton 作为 subview 。然后,为您的 sendBar 创建一个委托(delegate),并通过 sendBar 实现在您的主视图中触发它。

2:将sendButton作为 subview 直接添加到父 View ,而不是添加到sendBar。

UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height,50,50)];
sendButton.backgroundColor = [UIColor blackColor];
[sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
[self.navigationController.navigationBar addSubview:self.sendBar];
[self.sendBar addSubview:sendButton];
[self.view addSubview:sendButton];

此外,如果您只想将 sendBar 添加到 self.view 而不是添加到 self.navigationController.navigationBar ,则可能没问题;如果您只是希望它出现在 tableView 的顶部;但我不知道你正在尝试做的事情的全部范围。

关于ios - 以编程方式将 UIButton 添加到 UINavigationBar 的 subview 并且触摸事件未注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264624/

相关文章:

objective-c - 从 iOS 移植到 OS X

ios - Xcode 8.1 目标包含使用旧版本的 swift 开发的源代码

xcode - 停止打印 NSView

ios - 如何在 swift 中重新初始化惰性变量?

iphone - 内存管理困惑 Objective C

ios - 应用提交时缺少 NSMicrophoneUsageDescription 警告

ios - 如何跟踪同一 SKSpriteNode 的各个实例

ios - 多个 iOS 框架,如果主框架名称为 "Library Not loaded",则嵌套 "Network"问题

objective-c - 如何使用 self 创建对象?

ios - 如何在不使用多个 webview 的情况下更改 webview 的 url