项目中,需要使用self.navigationItem.titleView来设置titleview,并且要求达到和屏幕一样宽。
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
label.text = @"月未央";
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor redColor];
self.navigationItem.titleView = label;
单纯的设置frame,没有达到预想的效果,效果图如下:
两边总是留出部分“空隙”。查找相关资料,达到的解决方案如下:
继承UIView, 重写其中的setFrame方法。
@implementation GFTitleView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:CGRectMake(0, 0, self.superview.bounds.size.width, self.superview.bounds.size.height)];
}使用代码:
titleView = [[GFTitleView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
titleView.backgroundColor = [UIColor redColor];
self.navigationItem.titleView = titleView;
效果图:
在iOS项目中,使用self.navigationItem.titleView设置标题视图时,目标是使其宽度与屏幕宽度相等,但默认情况下会有两边的空隙。通过继承UIView并重写setFrame方法,可以实现titleView填充整个屏幕宽度的效果。

1945

被折叠的 条评论
为什么被折叠?



