[英]Navigationbar title alignment issue
我已將自定義視圖設置為導航欄titleView,當頁面是第一個視圖時,控制器標題在中心正確顯示
但是當從另一個視圖控制器推出視圖控制器時,控制器標題將向右移動
代碼:
-(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作為navigationItem
的titleView
。 這樣您就不必手動計算和調整其框架,它將自動由系統居中。 代碼中的范圍是硬編碼的。
// 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.