系統的導航列標題只能放一行文字,但很多時候我們想在標題位置放「文字 + 小按鈕」,或換成自訂的背景圖。這時只要自己組一個 view,指定給 navigationItem.titleView 就可以了。
// 建立 titleView 容器 UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 20)]; titleView.backgroundColor = [UIColor blackColor]; // 放一個 UILabel UILabel *titleText = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 50, 20)]; titleText.backgroundColor = [UIColor clearColor]; [titleText setText:@"Title"]; [titleView addSubview:titleText]; [titleText release]; // 再放一個系統樣式的 UIButton UIButton *btnNormal = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [btnNormal setFrame:CGRectMake(0, 0, 40, 20)]; [btnNormal addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside]; [btnNormal setTitle:@"Normal" forState:UIControlStateNormal]; [btnNormal.titleLabel setFont:[UIFont systemFontOfSize:8]]; [titleView addSubview:btnNormal]; // 掛上去 self.navigationItem.titleView = titleView; [titleView release];
UIButton *btnCustom = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [btnCustom setFrame:CGRectMake(0, 0, 32, 32)]; [btnCustom addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside]; [btnCustom setTitle:@"CB" forState:UIControlStateNormal]; [btnCustom setBackgroundImage:[UIImage imageNamed:@"whiteButton.png"] forState:UIControlStateNormal]; [btnCustom setBackgroundImage:[UIImage imageNamed:@"blueButton.png"] forState:UIControlStateHighlighted]; // 用 initWithCustomView: 把任意 view 包成 BarButtonItem UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnCustom]; self.navigationItem.rightBarButtonItem = rightBarButton; [rightBarButton release];
initWithCustomView: 是最通用的做法,任何 UIView 都能塞進去。