【发布时间】:2016-09-28 07:46:59
【问题描述】:
在这个小应用程序中,我只想制作一份问卷,在 UIView 上显示每个问题。由于问卷的大小可能会根据我的需要而改变,因此我想通过使用 for 循环和 NSMutableArray 来操作这些 UIView,从而使代码非常灵活。我用下面的代码创建了数组和视图,但是除了紫色的 UIScrollView 什么都没有显示。有人能指出为什么绿色的 UIViews 没有出现吗?
ViewController.h
@interface ViewController : UIViewController
@property (nonatomic, strong) NSMutableArray *viewArray;
@property UIView *question1View;
@property UIView *question2View;
@property UIView *question3View;
@property UIScrollView *questionScrollView;
ViewController.m
@implementation ViewController
@synthesize viewArray;
float viewHeight = 75.0;
float openViewHeight = 225.0;
float currentViewPossitionX = 0.0;
float currentViewPossitionY = 0.0;
float viewSpacing = 10.0;
int numberOfQuestions = 3;
- (void)viewDidLoad {
[super viewDidLoad];
[self setUpQuestionnaire];
}
- (void) setUpQuestionnaire{
self.viewArray[numberOfQuestions] = [[NSMutableArray alloc] init];
[viewArray insertObject: _question1View atIndex:0];
[viewArray insertObject: _question2View atIndex:1];
[viewArray insertObject: _question3View atIndex:2];
_question1View.backgroundColor = [UIColor greenColor];
_question2View.backgroundColor = [UIColor greenColor];
_question3View.backgroundColor = [UIColor greenColor];
float viewCount = 0;
_questionScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
_questionScrollView.backgroundColor = [UIColor purpleColor];
_questionScrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds),(CGRectGetHeight(self.view.bounds)+100));
[self.view addSubview:_questionScrollView];
for(int i = 0; i < numberOfQuestions; i++){
viewArray[i] = [[UIView alloc] initWithFrame:CGRectMake(currentViewPossitionX, currentViewPossitionY, CGRectGetWidth(_questionScrollView.bounds), viewHeight)];
[_questionScrollView addSubview:viewArray[i]];
viewCount++;
currentViewPossitionY += viewHeight + viewSpacing;
}
_questionScrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds),(viewHeight * viewCount + 500));
}
【问题讨论】:
-
属性'backgroundcolor'未找到
id类型的对象 -
抱歉,我发布了一个稍微旧的版本。我已经编辑了上面的代码以匹配。
-
你初始化你的 viewArray 数组了吗?正如我在您的代码中看到的那样 self.viewArray[numberOfQuestions] = [[NSMutableArray alloc] init];不是初始化数组代码
-
每次你的`_questionScrollView.bounds (origin = (x = 0, y = 0), size = (width = 375, height = 667))`都是一样的
-
所以你正在使用 _question1View=[[UIView alloc]init]; _question2View=[[UIView alloc]init]; _question3View=[[UIView alloc]init];
标签: ios objective-c uiview nsmutablearray