使用imageView自定义导航栏时存在间隙

时间:2012-08-24 10:18:08

标签: ios uiimageview uinavigationbar customization

我使用以下代码自定义带有UIView的导航栏。但为什么导航栏的左侧大小存在差距? PS。渐变图像是test.png。

提前致谢!

enter image description here

- (void)viewDidLoad
{
[super viewDidLoad];

// show image
UIImage *image = [UIImage imageNamed: @"test.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
[imageView setContentMode:UIViewContentModeScaleToFill];
imageView.frame = CGRectMake(0, 0, 320, 44);

// label
UILabel *tmpTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 0, 100, 44)];
tmpTitleLabel.text = @"title";
tmpTitleLabel.textAlignment = UITextAlignmentCenter;
tmpTitleLabel.backgroundColor = [UIColor clearColor];
tmpTitleLabel.textColor = [UIColor whiteColor];

CGRect applicationFrame = CGRectMake(0, 0, 320, 44);
UIView * newView = [[UIView alloc] initWithFrame:applicationFrame];
[newView addSubview:imageView];
[newView addSubview:tmpTitleLabel];
self.navigationItem.titleView = newView;
}

修改1

这是我的测试代码和屏幕截图

enter image description here

- (void)viewDidLoad
{    

[super viewDidLoad];

UIView * viewGreen = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIView * viewRed = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

[viewGreen setBackgroundColor:[UIColor greenColor]];
[viewRed setBackgroundColor:[UIColor redColor]];
self.navigationItem.titleView = viewRed;

[self.view addSubview:viewGreen];
}

2 个答案:

答案 0 :(得分:2)

你的代码工作正常。只需检查图像和透明度。

最后添加该行并再次检查

[self.view addSubview:newView];

答案 1 :(得分:1)

问题通过以下代码解决

[self.navigationBar insertSubview:imageView atIndex:1];