iPhone开发之九宫格实现(一)

总体思路:用图片定位。

//
// ViewController.m
// SquaresDemo
//
// Created by Fox on 12-3-21.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "NextView.h"

NextView *nextView;

@implementation ViewController


- (void)viewDidLoad
{
[super viewDidLoad];
//将每个图片作为一格,通过控制它的位置来实现九宫格。
NSArray* imageNames = [NSArray arrayWithObjects:
@"1.png",
@"1.png",
@"1.png",
@"1.png",
@"1.png",
@"1.png",
@"1.png",
@"1.png",
@"1.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];

}
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

//响应按钮事件
-(void)btnPressed:(id)sender{
NSLog(@"btnpress!");
UIButton *Btn = (UIButton *)sender;
int index = Btn.tag;

switch (index) {
case 0:
NSLog(@"2222");
if(nextView==nil)
nextView = [[NextView alloc]init];
[self.navigationController pushViewController:nextView animated:YES];
break;
//其他几个控制器类似
default:
if(nextView==nil)
nextView = [[NextView alloc]init];
[self.navigationController pushViewController:nextView animated:YES];

}

}

@end



你可能感兴趣的:(iPhone开发之九宫格实现(一))