将UIImage或UILabel添加到navigationItems

时间:2014-01-31 16:49:09

标签: ios uilabel uinavigationbar uibarbuttonitem uinavigationitem

在我的应用中,我必须根据我所在的页面自定义导航栏。在某些视图中,我需要添加一些UIButton,还有一些UIImage(对于未居中的徽标)或一些UILabel

我可以使用[self.navigationController.navigationBar addSubview:myLabel]来做到这一点。但我真的不喜欢这种方法,因为如果我必须添加UIButton或只是更改UILabel的文本,我需要手动更改每个UILabel的来源和每个UIImage

我想过使用已存在的东西:UIBarButtonItem。它可以包含一些文本,一个图像,我只需要在navigationItem.leftBarButtonItems中添加它们,并且每个东西都很好地定位。

唯一仍然存在的问题是它仍然是一个按钮,并在按下时作为一个按钮作出反应。如果我禁用它,它的alpha变化显示它被禁用...我怎么能保持它的正常表现,并让它被禁用?

谢谢!

PS:我对在导航栏中添加UIImages或UILabel的任何其他想法持开放态度:)

3 个答案:

答案 0 :(得分:2)

试试这段代码。您可以更改Label和imageView框架并将其作为您的要求。

UIView *btn = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];

UILabel *label;
label = [[UILabel alloc] initWithFrame:CGRectMake(5, 25, 200, 16)];
label.tag = 1;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:16];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = UITextAlignmentLeft;
label.textColor = [UIColor whiteColor];
label.text = @"My first lable";
label.highlightedTextColor = [UIColor whiteColor];
[btn addSubview:label];
[label release];

label = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 200, 16)];
label.tag = 2;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:16];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor whiteColor];
label.text = @"second line";
label.highlightedTextColor = [UIColor whiteColor];
[btn addSubview:label];
[label release];


UIImageView *imgviw=[[UIImageView alloc]initWithFrame:CGRectMake(170, 10, 20, 20)];
 imgviw.backgroundColor = [UIColor blackColor];
imgviw.image=[UIImage imageNamed:@"abc.png"];
 [btn addSubview:imgviw];

self.navigationItem.titleView = btn;

希望它有所帮助。

答案 1 :(得分:1)

您可以使用使用自定义视图创建的条形按钮。

例如,

UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0, 0, 100, 40)];
[btn setTitle:@"some Title" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor greenColor]];

self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:btn];

答案 2 :(得分:1)

您可以通过不为创建的按钮设置任何@selector,并为UIControlStateNormal和UIControlStateSelected设置相同的自定义属性来执行此操作。另外,将tintColor设置为ClearColor。像这样,按钮仍然是一个按钮,它将保持在那里,总是看起来一样,但它不会做任何事情。

希望它有所帮助。