我在导航栏中添加了自定义titleView。
在每个屏幕更改中,我都会添加另一个标题View。
问题是前一个没有删除,我可以一次查看所有视图。
这是我的代码:
UILabel *lblTitle = [[UILabel alloc] init];
lblTitle.text = text;
CGSize lblSize = [Utility sizeOfText:text withFont:kCGFontMedium(19)];
lblTitle.frame = CGRectMake(60, 9, lblSize.width, lblSize.height);
lblTitle.font =kCGFontMedium(19);
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor whiteColor];
[lblTitle sizeToFit];
[self.navigationController.navigationBar addSubview:lblTitle];
答案 0 :(得分:2)
解决方案1:每次必须删除添加到导航栏的自定义UIView对象
[self.navigationController.navigationBar.subviews enumerateObjectsWithOptions:0 usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isMemberOfClass:[UILabel class]]) {
[obj removeFromSuperview];
}
}];
UILabel *lblTitle = [UILabel new];
lblTitle.text = text;
CGSize lblSize = [Utility sizeOfText:text withFont:kCGFontMedium(19)];
lblTitle.frame = CGRectMake(60, 9, lblSize.width, lblSize.height);
lblTitle.font = kCGFontMedium(19);
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor whiteColor];
[lblTitle sizeToFit];
[self.navigationController.navigationBar addSubview:lblTitle];
解决方案2:在类接口中添加属性以存储对navigationBar中自定义子视图的访问
@property (weak, readwrite, nonatomic) UILabel *navSubView;
[self.lblTitle removeFromSuperview];
self.lblTitle = [UILabel new];
lblTitle.text = text;
CGSize lblSize = [Utility sizeOfText:text withFont:kCGFontMedium(19)];
lblTitle.frame = CGRectMake(60, 9, lblSize.width, lblSize.height);
lblTitle.font = kCGFontMedium(19);
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor whiteColor];
[lblTitle sizeToFit];
[self.navigationController.navigationBar addSubview:lblTitle];
答案 1 :(得分:0)
或者你可以使用NavigationItem" titleView"属性
UILabel * titleLabel = [[UILabel alloc] init];
UIView * titleView = [[UIView alloc] initWithFrame:titleLabel.frame]; [titleView addSubview:titleLabel];
self.navigationItem.titleView = titleView;
这将确保只存在一个标题标签实例,并且它不会与self.title重叠