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

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

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

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

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

  最后,修改 ViewController.m 中的 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]; //创建UIView控件
NSArray *appArray = [[NSBundle mainBundle] loadNibNamed:@"appxib" owner:nil options:nil];
WJQAppView *appView = [appArray firstObject];
appView.frame = CGRectMake(appViewX, appViewY, appViewWidth, appViewHeight);
appView.appImage.image = appInfo.image; //设置图片
appView.appLabel.text = appInfo.desc; //设置名称
appView.appButton.tag = i; //设置按钮的序号
[appView.appButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:appView];
}
}

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

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

上一篇:springcloud学习第一坑


下一篇:vab set dim