UINavigationBar左键上的customView

时间:2010-02-27 22:34:14

标签: iphone uinavigationbar uinavigationitem

我正在尝试使用自定义控件实现UINavigationBar。所以,我在UINavigationBar的左侧添加了UIView并尝试使用以下代码向该UIView添加控件:

UIView *view = navigationController.navigationItem.leftBarButtonItem.customView;
UIButton *button = [[UIButton alloc] initWithFrame:view.frame];
[button setTitle:@"TEST" forState:UIControlStateNormal];
[view addSubview:button];
[button sizeToFit];
[button release];

代码有效,但按钮不会出现。

任何帮助将不胜感激。 谢谢。

UPD

好的,我尝试了下面的代码并做了这样的事情:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 50)];
[button setTitle:@"XXX" forState:UIControlStateNormal];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
navigationController.visibleViewController.navigationItem.leftBarButtonItem = customItem;
[customItem release];
[button release];

确实出现了“XXX”标题,但它看起来像简单的标签,而不是按钮。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

是的,您的UIButton没有带任何阴影。我所做的是使用UISegmentedControl来免费获得阴影:

// Add the Menu button to the navigation bar
NSString* menuLabel = "ShadeButton";
CGSize textSize = [menuLabel sizeWithFont:[UIFont systemFontOfSize:15.0]];
UISegmentedControl* menuSegmentedButton = [[UISegmentedControl alloc]
    initWithFrame:CGRectMake(0.0f, 0.0f, textSize.width, 29.0f)];
menuSegmentedButton.momentary = YES;
menuSegmentedButton.selected = NO;
menuSegmentedButton.segmentedControlStyle = UISegmentedControlStyleBar;
[menuSegmentedButton insertSegmentWithTitle:menuLabel atIndex:0
                              animated:NO];
[menuSegmentedButton addTarget:self action:@selector(doMenu)
         forControlEvents:UIControlEventValueChanged];
UIBarButtonItem* barButton = [[UIBarButtonItem alloc] 
    initWithCustomView:menuSegmentedButton];
[menuSegmentedButton release];
self.navigationItem.rightBarButtonItem = barButton;

使用UISegmentedControl创建你的UIBarButtonItem,如上所示,而不是UIButton,你应该得到你想要的效果。另一种方法是在按钮上做更多的工作,并自己为它创建纹理/自定义图像。

答案 1 :(得分:3)

请注意。

如果您只是想要一个不同的标题:

UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithTitle:@"TEST" style:UIBarButtonItemStylePlain target:nil action:nil];
navigationController.navigationItem.leftBarButtonItem = customItem;
[customItem release];

如果您真的想要自定义视图:

// Create Custom View called myView.
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:myView];
navigationController.navigationItem.leftBarButtonItem = customItem;
[customItem release];