在這個小應用程序中,我只想製作一個調查問卷,在UIView上顯示每個問題。由於調查問卷的大小可能會根據我的需要而改變,因此我想通過使用for循環和NSMutableArray來操作這些UIViews,使代碼非常靈活。我用下面的代碼創建了數組和視圖,但是除了紫色的UIScrollView以外沒有任何東西出現。有人能指出爲什麼綠色的UIViews沒有顯示出來嗎?UIViews的NSMutableArray
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'類型的對象 –
對不起,發佈了一個稍微老一點的版本。我編輯了上面的代碼來匹配。 – nfoggia
你是否啓動了你的viewArray數組?就像我在你的代碼中看到的那樣self.viewArray [numberOfQuestions] = [[NSMutableArray alloc] init];是不是初始化數組代碼 – larva