不用 Storyboard、全部靠程式碼排版時,有幾個基本觀念要先記住。
1. UIView:加在 View 裡面的子控件,座標原點是父 View 的左上角,y 軸向下。
2. UIButton:Button 內部本身包含 UILabel 與 UIImageView。設定文字要用 setTitle:forState:,不要直接改 titleLabel.text,因為你不知道當前處於哪個狀態;字體則透過 titleLabel.font 設定。
3. 延遲載入:資料源陣列可以用 lazy loading,第一次被讀取時才建立。
排版的核心只有三個數字:總列數、單個項目的寬高、間距。有了這三個,位置就能全部算出來:
// 0. 總列數(一行最多 3 列) int totalColumns = 3; // 1. 應用的尺寸 CGFloat appW = 85; CGFloat appH = 90; // 2. 間距 =(控制器 view 的寬度 - 3 * 應用寬度)/ 4 CGFloat marginX = (self.view.frame.size.width - totalColumns * appW) / (totalColumns + 1); CGFloat marginY = 15;
marginX 的算法是關鍵:左右各留一個間距,中間每兩個項目之間也各留一個,所以是除以 (totalColumns + 1) 而不是 totalColumns - 1。這樣算出來的四邊留白才會一致。
- (void)viewDidLoad {
[super viewDidLoad];
int totalColumns = 3;
CGFloat appW = 85;
CGFloat marginX = (self.view.frame.size.width - totalColumns * appW) / (totalColumns + 1);
CGFloat marginY = 15;
// 3. 根據應用個數建立對應的 frame(index 0 ~ 11)
for (int index = 0; index < self.apps.count; index++) {
int col = index % totalColumns;
int row = index / totalColumns;
CGFloat appX = marginX + col * (appW + marginX);
CGFloat appY = 30 + row * (appH + marginY);
UIView *appView = [[UIView alloc] init];
appView.frame = CGRectMake(appX, appY, appW, appH);
appView.backgroundColor = [UIColor clearColor];
[self.view addSubview:appView];
NSDictionary *appInfo = self.apps[index];
// 圖示
CGFloat iconW = 45, iconH = 45;
CGFloat iconX = (appW - iconW) / 2;
CGFloat iconY = 0;
UIImageView *iconView = [[UIImageView alloc] init];
iconView.frame = CGRectMake(iconX, iconY, iconW, iconH);
iconView.image = [UIImage imageNamed:[appInfo objectForKey:@"icon"]];
[appView addSubview:iconView];
// 名稱
CGFloat nameW = appW, nameH = 20;
CGFloat nameX = 0;
CGFloat nameY = iconY + iconH + marginY;
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.frame = CGRectMake(nameX, nameY, nameW, nameH);
nameLabel.font = [UIFont systemFontOfSize:12];
nameLabel.text = [appInfo objectForKey:@"name"];
nameLabel.textAlignment = NSTextAlignmentCenter;
[appView addSubview:nameLabel];
// 下載按鈕
CGFloat downloadW = appW, downloadH = 20;
CGFloat downloadX = 12;
CGFloat downloadY = nameY + nameH;
UIButton *downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
downloadBtn.frame = CGRectMake(downloadX, downloadY, downloadW, downloadH);
downloadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
[downloadBtn setTitle:@"下載" forState:UIControlStateNormal];
[appView addSubview:downloadBtn];
}
}

純代碼排版最常見的痛點是「數字滿天飛」。建議把螢幕寬高、間距、字級都抽成常數或宏,後續要改設計稿時只需動一處。另外若同一種 cell 結構會重複出現,改用 UICollectionView 搭配自訂 UICollectionViewCell 會比手動算 frame 更好維護;若想保留手算方式,也可以考慮引入 Masonry 這類描述式佈局函式庫,讓約束關係寫在視覺上更靠近的位置。