简体   繁体   中英

Navigation Bar's Title View Overlaps

I have added a custom titleView in Navigation Bar.

In every screen change I am adding another title View.

The problem is that the previous one is not get removed and I can See all Views at a time.

Here is my code:

    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];

My Problem: Sign Up and Sign In overlaps 在此处输入图片说明

Solution 1: each time you have to remove the custom UIView object added to the navigation bar

[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];

Solution 2 : add the property in a class interface to store access to custom subview in the 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];

Or you could just use the NavigationItem's "titleView" property

UILabel *titleLabel = [[UILabel alloc] init];

UIView *titleView = [[UIView alloc] initWithFrame:titleLabel.frame];[titleView addSubview:titleLabel];

self.navigationItem.titleView = titleView;

This will ensure only one instance of title label exists, and it won't overlap the self.title either

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM