ios - 添加 UIImage 或 UILabel 到 navigationItems

标签 ios uilabel uinavigationbar uibarbuttonitem uinavigationitem

在我的应用程序中,我必须根据我所在的页面自定义导航栏。在某些 View 中,我需要添加一些 UIButton,还需要添加一些 UIImage(用于不居中的 Logo )或一些 UILabel

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

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

剩下的唯一问题是它仍然是一个按钮,并且在按下时会像一个按钮一样使用react。如果我禁用它,它的 alpha 变化会显示它已被禁用...我怎样才能保持它的正常外观,并让它被禁用?

谢谢!

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

最佳答案

试试这个代码片段。您可以根据需要更改 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;

希望对你有帮助。

关于ios - 添加 UIImage 或 UILabel 到 navigationItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21485507/

相关文章:

ios - 带有 FCM token 的设备的 Firebase 通知显示已发送但未收到

ios - 保存到相机胶卷后从路径加载特定图像

ios - 为什么使用 UIGraphicsPushContext/UIGraphicsPopContext

ios - 有 2 行的 UILabel,如何独立截断每行?

ios - 为iOS6/iO7打包UINavigationBar图片资源

ios - 是否可以添加一个 UIView 作为 UINavigationBar 的背景

Swift:固定导航栏过渡到另一个 View Controller

ios - SwipeGestureRecognizer 滑动速度超过阈值时调用函数

ios - Swift 更新 UILabel 与 dispatch_async 不工作

ios - UILabel 文本的多种文本颜色在 swift 3.0 中不起作用