您的位置:首页 > 移动开发 > IOS开发

iOS 设置titleview的宽度为屏幕宽

2015-10-24 17:00 330 查看
项目中,需要使用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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: