系統預設的 UIBarButtonItem 樣式有限,想要一個自訂外觀的導航欄按鈕,最直白的做法是寫一個 UIButton 的子類,把樣式細節全封裝起來,之後只要 new 一個出來放進 initWithCustomView: 即可。
#import <Foundation/Foundation.h>
@interface BlueButton : UIButton {
}
- (id)init;
@end
#import "BlueButton.h"
@implementation BlueButton
- (id)init {
if (self = [super init]) {
self.frame = CGRectMake(0, 0, 49.0, 30.0);
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
UIImage *image = [UIImage imageNamed:@"blueButton.jpg"];
UIImage *stretchImage =
[image stretchableImageWithLeftCapWidth:15.0 topCapHeight:0.0];
[self setBackgroundImage:stretchImage forState:UIControlStateNormal];
self.backgroundColor = [UIColor clearColor];
[self setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
self.titleShadowOffset = CGSizeMake(0, -1);
self.titleLabel.font = [UIFont boldSystemFontOfSize:13];
}
return self;
}
@end
這裡有兩個值得學的細節。第一是 stretchableImageWithLeftCapWidth:topCapHeight::把一張小圖指定左右可拉伸的區域後,就能用同一張素材撐出各種寬度的按鈕,不必為每個尺寸準備一張圖。第二是 titleShadowOffset 設為 (0, -1),搭配黑色陰影,是那個年代很常見的一種讓白字在淺色背景上更清楚的手法。
- (void)viewDidLoad {
[super viewDidLoad];
BlueButton *blueButton = [[BlueButton alloc] init];
[blueButton setTitle:@"Add" forState:UIControlStateNormal];
[blueButton addTarget:self action:@selector(add)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *button = [[UIBarButtonItem alloc]
initWithCustomView:blueButton];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:@selector(Cancel)];
self.navigationItem.rightBarButtonItem = button;
[button release];
[blueButton release];
}
左側沿用系統的 Cancel 樣式,右側換成自訂的 blueButton,這種「一邊系統、一邊自訂」的組合在表單頁面裡很實用。若同一頁有多顆相同樣式的按鈕,把樣式集中在子類中維護的好處會更明顯。
摘自 生活不是用來揮霍的