对的代码进行进一步优化。
新建一个 UIView 的子类,并命名为 WJQAppView ,将 appxib.xib 中的 UIView 对象与新建的视图类进行关联。
WJQAppView 类中声明3个 IBOutlet 属性,与 appxib.xib 中的视图对象包含的 UIImageView 、 UILabel 和 UIButton 建立连接。 WJQAppView 头文件代码如下所示:
1 //WJQAppView.h2 @interface WJQAppView : UIView3 @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 }
参考博客:
实例代码: