我在 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/