1

我正在尝试使用自定义控件实现 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”标题确实出现了,但它看起来像简单的标签,而不是按钮。有任何想法吗?

4

2 回答 2

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;

Create your UIBarButtonItem with the UISegmentedControl as shown above rather than a UIButton and you should get the effect you're after. The alternative is to do more work on the button and create a texture/custom image for it yourself.

于 2010-03-05T02:49:43.170 回答
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];
于 2010-02-27T22:44:54.770 回答