【问题标题】:Adding a UIButton Programmatically to a subview of UINavigationBar and touch events are not registering以编程方式将 UIButton 添加到 UINavigationBar 的子视图,并且触摸事件未注册
【发布时间】:2024-10-07 12:50:02
【问题描述】:

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

然后我以编程方式创建一个 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];

【问题讨论】:

    标签: ios objective-c xcode uibutton


    【解决方案1】:

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

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

    2:将sendButton作为子视图直接添加到父视图,而不是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];
    

    另外,如果您只是希望它出现在 tableView 的顶部,您可能只需将 sendBar 添加到 self.view 而不是 self.navigationController.navigationBar;但我不知道你想要做什么的全部范围。

    【讨论】:

      【解决方案2】:

      sendBar 框架不对,尝试设置为:

      CGRectMake(0, 0, self.view.frame.size.width,100) 
      

      sendBar 是 navigationBar 的子视图,通常高度为 64,因此您可能需要将高度 100 更改为 64。

      【讨论】:

        【解决方案3】:
        UIButton *right = [[UIButton alloc]initWithFrame:CGRectMake(0, 0,25, 20)]; 
        [right setBackgroundColor:[UIColor redColor]]; 
        [right setBackgroundImage:[UIImage imageNamed:@"imgPhoto"] forState:UIControlStateNormal]; 
        [right addTarget:self action:@selector(showRightClicked) forControlEvents:UIControlEventTouchUpInside]; 
        UIBarButtonItem *buttonItem1 = [[UIBarButtonItem alloc]initWithCustomView:right]; 
        self.navigationItem.leftBarButtonItem = buttonItem1;
        

        //如果要设置为右栏按钮则self.navigationItem.rightBarButtonItem = buttonItem1

        【讨论】: