无法定位自定义navigationItem titleView
Posted
技术标签:
【中文标题】无法定位自定义navigationItem titleView【英文标题】:Trouble positioning custom navigationItem titleView 【发布时间】:2016-02-19 18:30:31 【问题描述】:我有一个自定义视图 (titleView
),它是为我的 ios 应用上的 webView 创建的。 titleView
有两个标签,titleLabel
和 subTitleLabel
。如果titleLabel
对于titleView
来说太宽,我会截断文本并让它填满整个框架。但只要titleLabel
小于titleView
,就会出现问题。当我尝试计算titleLabel
框架的位置时,我得到不一致的结果。我只是假设我会取titelView.frame.size.width
和titleLabel.frame.size.width
的宽度之差除以2,但它不起作用。我可能错过了一些愚蠢的东西,但我只是看不到它。需要注意的一点是subTitleLabel
的定位似乎相当不错,虽然并不完美,但比titleLabel
的位置要好。
这里有一些图像(我在titleView
中添加了边框,它是帮助显示定位的子视图),它们显示了具有不同长度标题字符串的定位:
代码:
UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 88, 34)];
titleView.clipsToBounds = YES;
UIFont *titleFont = [UIFont systemFontOfSize:16 weight:UIFontWeightThin];
UIFont *speakerFont = [UIFont systemFontOfSize:10 weight:UIFontWeightLight];
CGSize speakerSize = [[self.speech speakerFullNameAndDate] sizeWithAttributes:@ NSFontAttributeName : speakerFont ];
CGSize titleSize = [self.speech.title sizeWithAttributes:@ NSFontAttributeName : titleFont ];
UILabel *titleLabel = [[UILabel alloc] init];
UILabel *subTitleLabel = [[UILabel alloc] init];
[titleView addSubview: titleLabel];
[titleView addSubview:subTitleLabel];
CGFloat titleDifference = (titleView.frame.size.width - titleLabel.frame.size.width) / 2;
titleLabel.text = self.speech.title;
titleLabel.font = titleFont;
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = [UIColor whiteColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
// titleLabel is bigger than the titleView's frame
if (titleSize.width > titleView.frame.size.width)
titleLabel.frame = CGRectMake(0, 0, titleView.frame.size.width - 20, 18);
else
// titleDifference / 3 seems to be the best number for the frame's x coordinate
titleLabel.frame = CGRectMake(titleDifference / 3, 0, titleSize.width, 18);
[titleLabel sizeToFit];
subTitleLabel.text = [self.speech speakerFullNameAndDate];
subTitleLabel.font = speakerFont;
subTitleLabel.textAlignment = NSTextAlignmentCenter;
subTitleLabel.textColor = [UIColor whiteColor];
subTitleLabel.backgroundColor = [UIColor clearColor];
// Again, ((titleView.frame.size.width - speakerSize.width) / 3) seems to work best, though it's far from perfect
subTitleLabel.frame = CGRectMake(((titleView.frame.size.width - speakerSize.width) / 3), 20, speakerSize.width, 12);
[subTitleLabel sizeToFit];
self.navigationItem.titleView = titleView;
【问题讨论】:
***.com/a/9269968/4475605 【参考方案1】:你计算你的标题标签原点错误记住任何视图原点都是左上角,所以你的标题标签原点应该是这样的
CGFloat originX = titelView.frame.size.width/2 - titleLabel.frame.size.width/2
您所做的是假设视图原点位于视图的中心
【讨论】:
以上是关于无法定位自定义navigationItem titleView的主要内容,如果未能解决你的问题,请参考以下文章
仅对 navigationItem backBarButton Item 使用自定义图像
iOS-自定义NavigationItem返回按钮pop返回按钮
自定义视图中的崩溃作为 UINavigationControllers navigationItem.titleView