我使用以下代码自定义带有UIView的导航栏。但为什么导航栏的左侧大小存在差距? PS。渐变图像是test.png。
提前致谢!
- (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
这是我的测试代码和屏幕截图
- (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];
}
答案 0 :(得分:2)
你的代码工作正常。只需检查图像和透明度。
最后添加该行并再次检查
[self.view addSubview:newView];
答案 1 :(得分:1)
问题通过以下代码解决
[self.navigationBar insertSubview:imageView atIndex:1];