很多同學在問九宮格怎麼實作,其實不難。這裡用的是最直覺的「圖片堆疊」思路:用一個迴圈產生九個 UIButton,靠座標計算排出三乘三的格子。
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *imageNames = [NSArray arrayWithObjects:
@"ico_mobile.png",
@"ico_idcard.png",
@"ico_postcode.png",
@"ico_flight.png",
@"ico_translate.png",
@"ico_phone.png",
@"ico_car.png",
@"ico_health.png",
@"ico_bjxm.png", nil];
UIButton *Btn;
for (int i = 0; i < 9; i++) {
CGRect frame;
Btn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
// 設置按鈕圖片
[Btn setImage:[UIImage imageNamed:[imageNames objectAtIndex:i]]
forState:UIControlStateNormal];
Btn.tag = i;
// 設置按鈕座標與大小
frame.size.width = 59;
frame.size.height = 75;
frame.origin.x = (i % 3) * (59 + 32) + 40;
frame.origin.y = floor(i / 3) * (75 + 24) + 40;
[Btn setFrame:frame];
[Btn setBackgroundColor:[UIColor clearColor]];
[Btn addTarget:self action:@selector(btnPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:Btn];
[Btn release];
}
}
排版的關鍵就在那兩行座標計算:i % 3 決定第幾欄、floor(i / 3) 決定第幾列,再乘上「按鈕尺寸 + 間距」並加上邊距,九宮格就自動攤開了。想改間距或起始位置,只要調整 32、24、40 這三個數字。
- (void)btnPressed:(id)sender {
UIButton *Btn = (UIButton *)sender;
int index = Btn.tag;
switch (index) {
case 0:
if (mobileController == nil)
mobileController = [[MobileController alloc] init];
[self.navigationController
pushViewController:mobileController animated:YES];
break;
// 其他幾個控制器類似
}
}
這裡用 tag 記住每顆按鈕的編號,事件回呼時再依編號分派到對應的控制器,不必為九個按鈕寫九個方法。
- (void)loadView {
UIImageView *contentView =
[[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[contentView setImage:[UIImage imageNamed:@"subview_9_bg.png"]];
[contentView setUserInteractionEnabled:YES];
self.view = contentView;
[contentView release];
}
用 UIImageView 當根視圖並設為可互動,就能自訂整頁背景;記得 setUserInteractionEnabled:YES,否則子按鈕會點不動。
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed:@"top_bg.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width,
self.frame.size.height)];
}
@end
透過 Category 覆寫 drawRect:,就能替整個 app 的導覽列換上同一張背景圖,不必逐一設定每個畫面。