将导航控制器中的UISegmentedControl和UIBarButtonItem组合到自定义的barbuttonitem背景图像

时间:2010-11-29 07:34:51

标签: iphone image background uibarbuttonitem uisegmentedcontrol

我有一个barbuttonitem,以编程方式在导航控制器上方。当我按下该按钮时,我想显示它的标题和背景以及突出显示的效果。 这是我使用的代码:

NSArray *segmentText = [segmentTextMutable copy];
UIImage *image = [[[UIImage alloc] init] autorelease];
image = [UIImage imageNamed:@"bunga.jpg"];

_docSegmentedControl = [[UISegmentedControl alloc] initWithItems:segmentText];
_docSegmentedControl.selectedSegmentIndex = 0;
_docSegmentedControl.autoresizingMask =  UIViewAutoresizingFlexibleHeight;
_docSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;
[_docSegmentedControl addTarget:self action:@selector(docSegmentAction:) forControlEvents:UIControlEventValueChanged];
[_docSegmentedControl setBackgroundColor:[UIColor colorWithPatternImage:image]];

UIView *barBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
UIButton *barButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"button.png"];
UIImage *buttonPressedImage = [UIImage imageNamed:@"buttonPressed.png"];
[[barButton titleLabel] setFont:[UIFont boldSystemFontOfSize:12.0]];
[barButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[barButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[barButton setTitleShadowColor:[UIColor colorWithWhite:1.0 alpha:0.7] forState:UIControlStateNormal];
[barButton setTitleShadowColor:[UIColor clearColor] forState:UIControlStateHighlighted];
[[barButton titleLabel] setShadowOffset:CGSizeMake(0.0, 1.0)];

 CGRect buttonFrame = CGRectMake(0, 0, 110.0, 40);
 //buttonFrame.size.width = 110.0;
 //buttonFrame.size.height = buttonFrame.size.height;
[barButton setFrame:buttonFrame];
[barButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[barButton setBackgroundImage:buttonPressedImage forState:UIControlStateHighlighted];
[barButton setTitle:docSegmentFileName forState:UIControlStateNormal];
[barButton addTarget:self action:@selector(docSegmentAction:) forControlEvents:UIControlEventTouchUpInside];
[barBackground addSubview:barButton];

UIBarButtonItem *segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
self.navItem.leftBarButtonItem = segmentItem;
self.navItem.leftBarButtonItem.title = @"";
[self.navItem.leftBarButtonItem setCustomView:barBackground];

不幸的是,这不起作用。它不是显示UIBarButtonItem,而是消失(它变得100%透明)。当我省略setCustomView方法时,会出现UIBarButtonItem,但不会自定义。我该如何解决这个问题?

感谢的......

1 个答案:

答案 0 :(得分:0)

当您调用[self.navItem.leftBarButtonItem setCustomView:barBackground];时,您正在从UIBarButtonItem中删除UISegmentedControl。您需要修改UISegmentedControl而不是UIBarButtonItem。