iPhone的九宫格实现代码

本文介绍了一种在iOS应用中实现九宫格界面的方法,通过加载不同图标并设置按钮位置来构造九宫格布局。此外,还展示了如何为UINavigationBar设置背景图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多开发者会在 iPhone 软件里用到手机上经典的九宫格界面,本段实现九宫格的代码由 CocoaChina 会员“花太香齐” 分享,博客原文地址 http://www.ieliwb.com/iphone-nine-box/




核心就这2个方法:


//Power by ieliwb.com


- (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];


    }


}


//响应按钮事件


-(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;


        //其他几个控制器类似


    }


}


 


九宫格背景修改可以这样实现:


- (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];


}


 


UINavigationBar背景图片可以这样实现:


@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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值