为什么通过UITabBarController.viewDidLoad中的代码添加的自定义按钮没有响应选择器

时间:2019-06-06 04:48:26

标签: ios swift uibutton

我在MyViewController.viewDidLoad(subclass of UITabBarController)的tabBar中添加了自定义按钮

但是我发现它没有响应选择器。

如果我延迟一秒钟添加按钮(in DispatchQueue.main.asyncAfter closure),则可以正常工作。

我认为这不是解决问题的正确方法。

func addButton() {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.bounds = CGRect(x:0,y:0,width:30,height:30);
        button.backgroundColor = UIColor.red
        button.center = CGPoint(x:self.tabBar.frame.size.width/2, y:self.tabBar.frame.size.height/2 - 20);
        button.addTarget(self, action: #selector(click(button:)), for: UIControl.Event.touchUpInside)
        tabBar.addSubview(button)
    }

1 个答案:

答案 0 :(得分:0)

您已将按钮添加到UITabBar的{​​{1}}中,因为按帧,按钮的一半将显示在选项卡栏的上方,而一半则显示在选项卡栏的下方。

Tabbar custode button

因此,我想您不会在该按钮的一部分上单击,而该按钮不在Tabbar(在Tabbar上方)不会接触。如果您将按钮调大一点,或者尝试在模拟器中用箭头单击,您将有想法。

如果您需要在底部有一个按钮,但在按钮的稍上方,请创建自定义标签栏以实现这样的设计。否则,您可以将该按钮而不是Tabbar添加到UITabBarController的视图中。

UITabBarController

我已经在行尾用数字标记了四件事,您可以对代码进行尝试。

Button in TabBarController