這是我會怎麼處理這個。希望它有幫助。 :)
CGRect contentFrame = CGRectMake(0, 0, self.view.frame.size.width, 0); // This will be the frame used to create the background image view.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(20, 20, 20, 20); // The margins by which the labels will be inset from the edge of their parent view.
CGFloat labelHeight = 21;
CGFloat verticalGap = 8; // The vertical space between labels
CGFloat y = contentInsets.top;
int numberOfLabels = 10;
for (int i = 0; i < numberOfLabels; i++) {
CGRect frame = CGRectMake(contentInsets.left, y, self.view.frame.size.width - (contentInsets.left + contentInsets.right), labelHeight);
UILabel *label = [[[UILabel alloc] initWithFrame: frame] autorelease];
// customize the label here
[self.view addSubview: label];
contentFrame = CGRectUnion(contentFrame, label.frame);
y += labelHeight + verticalGap;
}
contentFrame.size.height += contentInsets.bottom;
UIImageView *backgroundImageView = [[[UIImageView alloc] initWithFrame: contentFrame] autorelease];
[backgroundImageView setClipsToBounds: YES];
[backgroundImageView setContentMode: UIViewContentModeScaleAspectFill];
[backgroundImageView setImage: [UIImage imageNamed: @"background_image.png"]];
[self.view insertSubview: backgroundImageView atIndex: 0];
謝謝 - 但我如何確保大小匹配使用約束(我不使用IB)?如果我設置了一個約束,使得視圖的大小==,視圖只是展開以滿足該約束(而不是圖像縮小)。不幸的是,我無法硬編碼視圖的固定高度,因爲大小取決於內容。 –
您可以覆蓋'layoutSubviews'並確保背景圖像視圖的大小相同。 – Mundi
我想我們應該調用'layoutIfNeeded' – onmyway133