對iOS開發基礎-九宮格座標(3)的代碼進行進一步優化。html
新建一個 UIView 的子類,並命名爲 WJQAppView ,將 appxib.xib 中的 UIView 對象與新建的視圖類進行關聯。app
WJQAppView 類中聲明3個 IBOutlet 屬性,與 appxib.xib 中的視圖對象包含的 UIImageView 、 UILabel 和 UIButton 創建鏈接。 WJQAppView 頭文件代碼以下所示:ide
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的簡單使用atom
實例代碼:http://pan.baidu.com/s/1o7l6IXc spa