如何自定义titleView的宽度

前言

下面的代码,定义了titleView的宽度为屏幕宽度。

UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
titleView.backgroundColor = [UIColor redColor];
self.navigationItem.titleView = titleView;

实际效果:


截图1

效果并不理想。

解决方案

一、创建个UIView类:

@interface CustomTitleView : UIView
@end

@implementation CustomTitleView

- (instancetype)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)];
}

@end

二、调用

UIView *titleView = [[CustomTitleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
titleView.backgroundColor = [UIColor greenColor];
self.navigationItem.titleView = titleView;

最终效果

截图2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,738评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,233评论 4 61
  • 一. 网络应用程序设计模式C/S - client/server 协议灵活, 可缓存数据, 但是开发量大B/S...
    wulegekong阅读 2,720评论 0 3
  • 主持人:刘晓雁 文字记录:张莉 时间郎:邢衍贞 排麦大臣:邢衍贞 班会主题:善用工具,让你达到事半功倍。 首...
    刘晓雁阅读 1,677评论 0 1
  • 来漓江有点阴阳差错,本来打算是去阳朔的。在高铁上,用携程网订了家看起来有情味的客栈。出了车站,客栈的车便接上了...
    杨杰子江阅读 4,114评论 2 2