gpt4 book ai didi

ios - 导航栏标题对齐问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:39 26 4
gpt4 key购买 nike

我已将自定义 View 设置为导航栏 titleView,当页面是第一个时, View Controller 标题在中心正确显示

Correct Image

但是当从另一个 View Controller 推送 View Controller 时,标题向右移动

Incorrect Image

代码:

-(void)setUpTwoLineNavigationTitle {
CGFloat width = 0.95 * self.view.frame.size.width;
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 44)];
contentView.backgroundColor = [UIColor clearColor];

CGRect titleRect = contentView.frame;
titleRect.origin.y = 4;
titleRect.size.height = 20;

UILabel *titleView = [[UILabel alloc] initWithFrame:titleRect];
titleView.backgroundColor = [UIColor clearColor];
titleView.font = [UIFont systemFontOfSize:14.0];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor blackColor];
titleView.text = @"";
[contentView addSubview:titleView];

CGRect subTitleRect = contentView.frame;
subTitleRect.origin.y = 24;
subTitleRect.size.height = subTitleRect.size.height - 24;
//CGRect subtitleFrame = CGRectMake(0, 24, 220, 44-24);
UILabel *subtitleView = [[UILabel alloc] initWithFrame:subTitleRect];
subtitleView.backgroundColor = [UIColor clearColor];
subtitleView.font = [UIFont systemFontOfSize:11.0];
subtitleView.textAlignment = NSTextAlignmentCenter;
subtitleView.textColor = [UIColor blackColor];
subtitleView.text = @"";
[contentView addSubview:subtitleView];

contentView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
self.navigationItem.titleView = contentView;
}

谁能帮我改正这个问题?

Github 链接:https://github.com/iamabhiee/NavigationTitleDemo

最佳答案

这里有一个解决方法,它可能有用,想法是使用 UILabel 作为 navigationItemtitleView。这样你就不用手动计算和调整它的边框了,它会由系统自动居中。不过,代码中的范围是硬编码的。

// here to create a UILabel
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.numberOfLines = 0;

// set different font for title and subtitle
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"Title\nSubTitle"];
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0] range:NSMakeRange(0,5)];
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11.0] range:NSMakeRange(6,8)];

// set line spacing
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setLineSpacing:6];
[paragrahStyle setAlignment:NSTextAlignmentCenter];
[string addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [string length])];

label.attributedText = string;
[label sizeToFit];

self.navigationItem.titleView = label;

关于ios - 导航栏标题对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com