我只需要找出有關iOS視圖和佈局的幾件事情。我剛剛結束了應用程序,我必須創建一個顯示測試的控制器。除了一件事情,這很容易。有兩種類型的問題A和B.一個問題有4個答案變種,B個問題沒有。所以我不得不根據問題類型生成代碼中的所有佈局。我已經通過創建方法update
完成了我在那裏重建我的視圖。動態視圖控制器
- (void)update {
for (UIView *v in self.view.subviews) {
[v removeFromSuperview];
}
//label initialization with frame calculation
UILabel *questionLabel = [[UILabel alloc]initWithFrame:CGRectMake(PADDING, PADDING, size.width - 4 * PADDING, 0)];
[questionLabel sizeToFit];
[self.view addSubview:questionContainerView];
//If type A
if ([self.question.questionType isEqualToString:@"A"]) {
for (Answer *a in self.question.answers) {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(PADDING, offset, size.width - 2 * PADDING, 30 + PADDING)];
//customization
[self.view addSubview:button];
offset += button.frame.size.height + MARGIN_BOTTOM;
}
//if B type
} else {
UITextField *answerField = [[UITextField alloc] initWithFrame:CGRectMake(PADDING, PADDING, view.frame.size.width - 2*PADDING, view.frame.size.height - 2 * PADDING)];
[view addSubview:answerField];
offset += view.frame.size.height + MARGIN_BOTTOM;
}
UIView *lastView = [[self.view subviews]lastObject];
self.scrollView.contentSize = CGSizeMake(size.width, lastView.frame.origin.y + lastView.frame.size.height + 10);
}
而畢竟我認爲它不可能如此複雜。請幫助找出我該如何正確地做,因爲我確信我的方法不是最佳的。也許創建自定義佈局。我的意思是如何避免設置框架,並簡單地添加正確位置的視圖。