iOS开发基础-九宫格坐标(4)

  对iOS开发基础-九宫格坐标(3)的代码进行进一步优化。

  新建一个 UIView 的子类,并命名为 WJQAppView ,将 appxib.xib 中的 UIView 对象与新建的视图类进行关联。

   WJQAppView 类中声明3个 IBOutlet 属性,与 appxib.xib 中的视图对象包含的 UIImageView 、 UILabel 和 UIButton 建立连接。 WJQAppView 头文件代码如下所示:

1 //WJQAppView.h
2 @interface WJQAppView : UIView
3 @property (weak, nonatomic) IBOutlet UIImageView *appImage;
4 @property (weak, nonatomic) IBOutlet UILabel *appLabel;
5 @property (weak, nonatomic) IBOutlet UIButton *appButton;
6 @end

  最后,修改 ViewController.m 中的 viewDidLoad 方法:

 1 //ViewController.m
 2 - (void)viewDidLoad {
 3     [super viewDidLoad];
 4     
 5     int totalColumn = 3;        //3列
 6     CGFloat margin = (self.view.frame.size.width - totalColumn*appViewWidth) / (totalColumn + 1);
 7     int count = self.apps.count;
 8     NSLog(@"%d", count);
 9     
10     for (int i = 0; i < count; i++) {
11         int row = i/totalColumn;        //行号,从0开始
12         int column = i%totalColumn;     //列号,从0开始
13         CGFloat appViewX = margin + (margin + appViewWidth) * column;       //子视图的X坐标
14         CGFloat appViewY = margin + (margin + appViewHeight) * row;      //子视图的Y坐标
15         WJQAppInfo *appInfo = self.apps[i];
16         
17         //创建UIView控件
18         NSArray *appArray = [[NSBundle mainBundle] loadNibNamed:@"appxib" owner:nil options:nil];
19         WJQAppView *appView = [appArray firstObject];
20         appView.frame = CGRectMake(appViewX, appViewY, appViewWidth, appViewHeight);
21         appView.appImage.image = appInfo.image;      //设置图片
22         appView.appLabel.text = appInfo.desc;        //设置名称
23         appView.appButton.tag = i;                   //设置按钮的序号
24         [appView.appButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
25         
26         [self.view addSubview:appView];
27     }
28 }

 

参考博客:iOS开发UI篇—xib的简单使用

实例代码:http://pan.baidu.com/s/1o7l6IXc 

posted @ 2016-01-13 19:16  pestle  阅读(254)  评论(0编辑  收藏  举报