您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 客製化 UINavigationItem:自寫 titleView

編輯:iOS 開發綜合

系統的導航列標題只能放一行文字,但很多時候我們想在標題位置放「文字 + 小按鈕」,或換成自訂的背景圖。這時只要自己組一個 view,指定給 navigationItem.titleView 就可以了。

一、組一個含文字與按鈕的 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];

三、幾個實務提醒

  • titleView 的高度請控制在導航列可用範圍內(約 44pt 上下),過高會被裁切。
  • 內部子視圖記得把縱向位置算好,因為 titleView 會被置中對齊,高度不足時容易偏移。
  • 要在 BarButtonItem 裡放自訂樣式,initWithCustomView: 是最通用的做法,任何 UIView 都能塞進去。
  • 在 ARC 專案中不需要手動 release,上面示範保留是為了對應原始 MRC 寫法。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved