前言
下面的代码,定义了titleView的宽度为屏幕宽度。
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
titleView.backgroundColor = [UIColor redColor];
self.navigationItem.titleView = titleView;
实际效果:
效果并不理想。
解决方案
一、创建个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;