iOS 设置titleview的宽度为屏幕宽

来源:互联网 发布:switch case用法 java 编辑:程序博客网 时间:2024/05/01 14:37

项目中,需要使用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;

效果图:


1 0
原创粉丝点击