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

时间:2023-03-09 18:40:26
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 文件的画布中,设置其属性为:

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

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

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

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

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

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

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

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

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

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

  效果图如下所示:

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

三、代码实现

  修改 viewDidLoad 方法如下所示:

 //ViewController.m
- (void)viewDidLoad {
[super viewDidLoad]; int totalColumn = ; //3列
CGFloat margin = (self.view.frame.size.width - totalColumn*appViewWidth) / (totalColumn + );
int count = self.apps.count;
NSLog(@"%d", count); for (int i = ; i < count; i++) {
int row = i/totalColumn; //行号,从0开始
int column = i%totalColumn; //列号,从0开始
CGFloat appViewX = margin + (margin + appViewWidth) * column; //子视图的X坐标
CGFloat appViewY = margin + (margin + appViewHeight) * row; //子视图的Y坐标
WJQAppInfo *appInfo = self.apps[i]; //加载xib文件,并创建UIView控件
NSArray *appArray = [[NSBundle mainBundle] loadNibNamed:@"appxib" owner:nil options:nil];
UIView *appView = [appArray firstObject];
appView.frame = CGRectMake(appViewX, appViewY, appViewWidth, appViewHeight);
//创建上述UIView控件的子视图,创建图像信息
UIImageView *appImageView = (UIImageView *)[appView viewWithTag:];
appImageView.image = appInfo.image; //设置图片
//创建上述UIView控件的子视图,创建UILabel信息描述标签
UILabel *appLabel = (UILabel *)[appView viewWithTag:];
appLabel.text = appInfo.desc;
//创建下载按钮
UIButton *appButton = (UIButton *)[appView viewWithTag:];
[appButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
appButton.tag = i; [self.view addSubview:appView];
}
}

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

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