在 iOS 開發中,若直接將 UIImageView 加入視圖卻未設定框架,執行時會出現黑屏。這是因為視圖缺乏具體的位置與尺寸資訊。以下示範如何正確設置框架並啟用自動調整遮罩,確保視圖在父視圖尺寸改變時能自動適應。
UIView *baseView = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:baseView];
// 顯示 UIImageView
UIImageView *myImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tool.png"]];
myImage.frame = baseView.bounds;
[baseView addSubview:myImage];
baseView 指定 initWithFrame:,使用 self.view.bounds 使其填滿畫面。myImage.frame 設為 baseView.bounds,讓圖片佔滿容器。baseView 與 myImage 設置 autoresizingMask,例如 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight,當父視圖框架改變時,兩個視圖都能自動調整大小。遵循上述步驟,即可避免黑屏問題,並確保圖片在不同螢幕尺寸或旋轉時正確顯示。