歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iPhone九宮格的實現

iPhone九宮格的實現

日期:2017/3/1 10:36:07   编辑:Linux編程

看到很多同學在問,其實很簡單,我這是用圖片堆砌實現的九宮格,分享如下:

效果圖:

核心就這2個方法:

[plain]

  1. //Power by ieliwb.com
  2. - (void)viewDidLoad {
  3. [super viewDidLoad];
  4. NSArray* imageNames = [NSArray arrayWithObjects:
  5. @"ico_mobile.png",
  6. @"ico_idcard.png",
  7. @"ico_postcode.png",
  8. @"ico_flight.png",
  9. @"ico_translate.png",
  10. @"ico_phone.png",
  11. @"ico_car.png",
  12. @"ico_health.png",
  13. @"ico_bjxm.png", nil];
  14. UIButton *Btn;
  15. for (int i=0; i<9; i++) {
  16. CGRect frame;
  17. Btn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
  18. [Btn setImage:[UIImage imageNamed:[imageNames objectAtIndex: i]]forState:UIControlStateNormal];//設置按鈕圖片
  19. Btn.tag = i;
  20. frame.size.width = 59;//設置按鈕坐標及大小
  21. frame.size.height = 75;
  22. frame.origin.x = (i%3)*(59+32)+40;
  23. frame.origin.y = floor(i/3)*(75+24)+40;
  24. [Btn setFrame:frame];
  25. [Btn setBackgroundColor:[UIColor clearColor]];
  26. [Btn addTarget:self action:@selector(btnPressed:)forControlEvents:UIControlEventTouchUpInside];
  27. [self.view addSubview:Btn];
  28. [Btn release];
  29. }
  30. }
  31. //響應按鈕事件
  32. -(void)btnPressed:(id)sender{
  33. UIButton *Btn = (UIButton *)sender;
  34. int index = Btn.tag;
  35. switch (index) {
  36. case 0:
  37. if(mobileController==nil)
  38. mobileController = [[MobileController alloc]init];
  39. [self.navigationController pushViewController:mobileControlleranimated:YES];
  40. break;
  41. //其他幾個控制器類似
  42. }
  43. }
九宮格背景修改可以這樣實現:

[plain]

  1. - (void)loadView {
  2. UIImageView *contentView = [[UIImageView alloc] initWithFrame:[[UIScreenmainScreen] applicationFrame]];
  3. [contentView setImage:[UIImage imageNamed:@"subview_9_bg.png"]];
  4. [contentView setUserInteractionEnabled:YES];
  5. self.view = contentView;
  6. [contentView release];
  7. }
  8. UINavigationBar背景圖片可以這樣實現:
  9. @implementation UINavigationBar (CustomImage)
  10. - (void)drawRect:(CGRect)rect {
  11. UIImage *image = [UIImage imageNamed: @"top_bg.png"];
  12. [image drawInRect:CGRectMake(0, 0, self.frame.size.width,self.frame.size.height)];
  13. }
  14. @end
Copyright © Linux教程網 All Rights Reserved