自訂NavigationBar
功能需求在NavigationBar上添加搜尋方塊,並對其位置提出了要求,系統中內建的TitleView不能滿足,因此查閱了資料,重寫了TitleView
TitleView.h檔案,重寫TitleView繼承UIView
#import <UIKit/UIKit.h>@interface TitleView : UIView@end
TitleView.m檔案,重寫其父類的Frame
#import "TitleView.h"@implementation TitleView- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { } return self;}- (void)setFrame:(CGRect)frame { [super setFrame:CGRectMake(0, 0, self.superview.frame.size.width, self.superview.bounds.size.height)];}@end
在需要使用的地方引用
// 這裡之所以要把leftBarButtonItem的title = @“”,設為了防止介面從上一層pushViewController:或是從該介面popViewControllerAnimated:是顯示出系統內建的返回箭頭 UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] init]; [backButtonItem setTitle:@""]; self.navigationItem.leftBarButtonItem = backButtonItem; _titleView = [[TitleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)]; _titleView.backgroundColor = [UIColor blackColor]; self.navigationItem.titleView = _titleView;