我想在navigationBar中更改图片,backButton的标题和颜色。代码如下:
UIButton* backButton = (UIButton *) [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BackButtonTopBar.png"]];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.navigationItem.leftBarButtonItem = backButtonItem;
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
UIImage *image = [UIImage imageNamed: @"TopBar.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
self.navigationItem.titleView = imageView;
但我有一些问题:
所以有人可以帮助我吗?感谢。
答案 0 :(得分:1)
UIButton * backButton = [UIButton buttonWithType:101];
[backButton setBackgroundImage:[UIImage imageNamed:BACK_BUTTON_IMAGE_NORMAL] forState:UIControlStateNormal];
[backButton setBackgroundImage:[UIImage imageNamed:BACK_BUTTON_PRESSED] forState:UIControlStateHighlighted];
UIView * backButtonView = [[UIView alloc] initWithFrame:CGRectMake(BACK_BUTTON_FRAME)];
[backButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[backButtonView addSubview:backButton];
UIBarButtonItem * backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
self.navigationItem.leftBarButtonItem = backBarButton;
[backButtonView release];
[backBarButton release];
答案 1 :(得分:0)
这行代码意味着什么?
UIButton* backButton = (UIButton *) [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BackButtonTopBar.png"]];
如果您需要创建按钮,则必须执行以下操作。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
然后将背景图像设置为它。
但我喜欢的方式是为UIBarButtonItem
创建类别扩展,如下所示
//UIBarButtonItem+YourPreferredName.h
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image title:(NSString*)title target:(id)target action:(SEL)action;
//UIBarButtonItem+YourPreferredName.m
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image title:(NSString*)title target:(id)target action:(SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
// additional customizations here...
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
return [barButtonItem autorelease];
}
如果您在需要的地方导入UIBarButtonItem+YourPreferredName.h
,则可以使用以下内容:
UIBarButtonItem* backBarButtonItem = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"YoutImageName"] title:@"YourTitle" target:self action:@selector(goBack:)];
其中goBack
可以是以下内容:
- (void)goBack:(id)sender
{
// do stuff here
}
希望它有所帮助。