iOS开发基础-九宫格坐标(3)之Xib

  延续iOS开发基础-九宫格坐标(2)的内容,对其进行部分修改。

  本部分采用 Xib 文件来创建用于显示图片的 UIView 对象。

一、简单介绍

   Xib 和 storyboard 的比较:

  1) Xib 是轻量级的,用来描述局部的UI界面;

  2) storyboard 是重量级的,用来描述整个软件的多个界面,并且能演示多个界面之间的连接关系。

二、 Xib 的简单使用

  按照 Command + N ----> User Interface ----> Empty 新建一个 Xib 文件,并命名为 appxib ,其后缀名为 .xib 。

  将 UIView 对象拖到 appxib.xib 文件的画布中,设置其属性为:

             

  向 UIView 中拖入 UIImageView 对象,设置其属性为:

     

 

  向 UIView 中拖入 UILabel 对象,设置其属性为:

     

  向 UIView 中拖入 UIButton 对象,设置其属性为:

     

   为了使UIButton 对象为圆角矩形,在 Identity Inspector 的 User Defined Runtime Attributes 中添加 layer.cornerRadius 属性,如下所示:

      

  最后,将 UIImageView 、 UILabel 和 UIButton 的 tag 属性分别设置为1,2,3。

  效果图如下所示:

      

三、代码实现

  修改 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         //加载xib文件,并创建UIView控件
18         NSArray *appArray = [[NSBundle mainBundle] loadNibNamed:@"appxib" owner:nil options:nil];
19         UIView *appView = [appArray firstObject];
20         appView.frame = CGRectMake(appViewX, appViewY, appViewWidth, appViewHeight);
21         //创建上述UIView控件的子视图,创建图像信息
22         UIImageView *appImageView = (UIImageView *)[appView viewWithTag:1];
23         appImageView.image = appInfo.image;      //设置图片
24         //创建上述UIView控件的子视图,创建UILabel信息描述标签
25         UILabel *appLabel = (UILabel *)[appView viewWithTag:2];
26         appLabel.text = appInfo.desc;
27         //创建下载按钮
28         UIButton *appButton = (UIButton *)[appView viewWithTag:3];
29         [appButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
30         appButton.tag = i;
31         
32         [self.view addSubview:appView];
33     }
34 }

 

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

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

  

posted @ 2016-01-12 20:21  pestle  阅读(603)  评论(0编辑  收藏  举报