简体   繁体   English

使用按钮在UINavigationBar中添加子视图不起作用

[英]adding subviews in UINavigationBar with buttons doesn't work

I have a UINavigationController subclass and in the viewDidLoad I had the following code: 我有一个UINavigationController子类,在viewDidLoad中我有以下代码:

self.containerView_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, self.navigationController.navigationBar.frameHeight)];
    [self.containerView_ setBackgroundColor:[UIColor yellowColor]];
    [self.containerView_ setAutoresizingMask:UIViewAutoresizingNone];

    self.profileButton_ = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [self.profileButton_ addTarget:self action:@selector(showProfileView:) forControlEvents:UIControlEventTouchUpInside];
    [self.profileButton_ setCenterY:self.navigationController.navigationBar.frameHeight/2];
    [self.profileButton_ setImage:[UIImage imageNamed:@"profile_icon.png"] forState:UIControlStateNormal];

    self.socialButton_ = [[UIButton alloc] initWithFrame:CGRectMake(self.profileButton_.frameRight + 10, 0, 30, 30)];
    [self.socialButton_ addTarget:self action:@selector(showSocialView:) forControlEvents:UIControlEventTouchUpInside];
    [self.socialButton_ setCenterY:self.profileButton_.centerY];
    [self.socialButton_ setImage:[UIImage imageNamed:@"social_icon.png"] forState:UIControlStateNormal];

    self.notesButton_ = [[UIButton alloc] initWithFrame:CGRectMake(self.socialButton_.frameRight + 10, 0, 30, 30)];
    [self.notesButton_ addTarget:self action:@selector(showNotesView:) forControlEvents:UIControlEventTouchUpInside];
    [self.notesButton_ setCenterY:self.profileButton_.centerY];
    [self.notesButton_ setImage:[UIImage imageNamed:@"notes_icon.png"] forState:UIControlStateNormal];


    [self.containerView_ addSubview:self.profileButton_];
    [self.containerView_ addSubview:self.notesButton_];
    [self.containerView_ addSubview:self.socialButton_];

    [self.navigationBar addSubview:self.containerView_];

I can see the UIButton but the container background is not even yellow color. 我可以看到UIButton,但容器背景甚至不是黄色。 When I press the button, the action of the UIButton is not called. 当我按下按钮时,不会调用UIButton的动作。 Any idea why this is? 知道为什么会这样吗?

You are subclassing UINavigationController? 你是UINavigationController的子类?

To quote Apple: "This class is not intended for subclassing." 引用Apple:“这个类不用于子类化。”

The usual way to tweak the UINavController is to access the navBar from the perspecitve of a contained UIViewController. 调整UINavController的常用方法是从包含的UIViewController的perspecitve访问navBar。 You would put the target/action methods in the UIViewController. 您可以将目标/操作方法放在UIViewController中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM