使用customView时UINavigationBarButton无法正常工作

时间:2017-11-30 16:49:27

标签: objective-c uiview uinavigationbar custom-view programmatically

我想创建一个包含图像和文本的自定义UIBarButtonItem,还可以自定义(缩小)UIButton点击区域。为了以编程方式实现此目的,我使用以下代码段。但是当UIView作为子视图添加时,UIButton会消失。有人可以指导我出了什么问题吗? 为了减少bar按钮的tap区域,我在自定义UIView中嵌入了自定义UIButton。

//Set Navigation Bar
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];

//Set title if needed
UINavigationItem * navTitle = [[UINavigationItem alloc] init];
navTitle.title = @"";
UIView *customBackView = [[UIView alloc] initWithFrame:CGRectMake(220,0,50,40)];
customBackView.backgroundColor = [UIColor clearColor];

//Here you create info button and customize it
UIButton * tempButton = [UIButton buttonWithType:UIButtonTypeSystem];
tempButton.frame=CGRectMake(240,2,40,40);
[tempButton setImage:[UIImage imageNamed:@"offline_bk.png"]
         forState:UIControlStateNormal];

//Add selector to info button
[tempButton addTarget:self action:@selector(onTapDone:) forControlEvents:UIControlEventTouchUpInside];
[customBackView addSubview:tempButton];
[customBackView bringSubviewToFront:tempButton];
UIBarButtonItem * infoButton = [[UIBarButtonItem alloc] initWithCustomView:customBackView];

//In this case your button will be on the right side
navTitle.rightBarButtonItem = infoButton;

//Add NavigationBar on main view
navBar.items = @[navTitle];
[self.view addSubview:navBar];

1 个答案:

答案 0 :(得分:1)

因为你的tempbutton超出了自定义后视图的范围。您将y原点值设置为2,将x原点值设置为240,这会导致按钮超出自定义后视图的范围。

试试这段代码:

 UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];

    //Set title if needed
    UINavigationItem * navTitle = [[UINavigationItem alloc] init];
    navTitle.title = @"";
    UIView *customBackView = [[UIView alloc] initWithFrame:CGRectMake(0,0,50,50)];
    customBackView.backgroundColor = [UIColor clearColor];

    //Here you create info button and customize it
    UIButton * tempButton = [UIButton buttonWithType:UIButtonTypeSystem];
    tempButton.frame=CGRectMake(4,2,40,40);
    [tempButton setImage:[UIImage imageNamed:@"offline_bk.png"]
                forState:UIControlStateNormal];

    //Add selector to info button
    [tempButton addTarget:self action:@selector(onTapDone:) forControlEvents:UIControlEventTouchUpInside];
    [customBackView addSubview:tempButton];
    [customBackView bringSubviewToFront:tempButton];
    UIBarButtonItem * infoButton = [[UIBarButtonItem alloc] initWithCustomView:customBackView];

    //In this case your button will be on the right side
    navTitle.rightBarButtonItem = infoButton;

    //Add NavigationBar on main view
    navBar.items = @[navTitle];
    [self.view addSubview:navBar];
    [self.view bringSubviewToFront:navBar];