2016-03-20 1 views
0

基本的な質問で私を助けてください:配列からすべてのオブジェクトを取り出し、別の配列からそのプロパティを設定してください

私はオブジェクトの配列を持っています。そして別の配列(それは色と仮定します。)私は最初の配列からすべてのオブジェクトを取得し、別の配列からプロパティ(setBackgroundColor)を順次設定する便利な方法を探しています。ここに私のタラです。

@interface ViewController() 

_arrayWithColors = [[NSMutableArray alloc]initWithObjects:[UIColor blackColor],[UIColor orangeColor], [UIColor blueColor], [UIColor purpleColor], nil]; 

_arrayWithViews = [[NSMutableArray alloc]initWithObjects:view1,view2,view3,view4, nil]; 

    for (int i = 0; i<[_arrayWithViews count];i++) { 
     [[_arrayWithViews objectAtIndex:i] setBackgroundColor:[self setColor:i]]; 
     [self.view addSubview:[_arrayWithViews objectAtIndex:i]]; 
    } 

} 
-(UIColor*)setColor:(NSInteger) index { 
    _arrayWithColors = [[NSMutableArray alloc]initWithObjects:[UIColor blackColor],[UIColor orangeColor], [UIColor blueColor], [UIColor purpleColor], nil]; 
    return [_arrayWithColors objectAtIndex:index]; 
} 

他の配列の色を返すメソッドを作成します。 誰かがこの操作を行う良い方法を知っているのでしょうか?

+0

setColorメソッドにはあまり価値がありません。また、参照するたびにカラー配列を再作成する行には何もありません。安全のためには、少なくともビューと同じ色があることを確認する必要があります。 –

答えて

0

@PhillipMillsコメントを説明するには、カラー配列を一度作成し、インデックスがカラー配列の範囲内にあることを確認する必要があります。

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    _arrayWithViews = [[NSMutableArray alloc]initWithObjects:view1,view2,view3,view4, nil]; 

    for (int i = 0; i<[_arrayWithViews count];i++) { 
     [[_arrayWithViews objectAtIndex:i] setBackgroundColor:[self getColor:i]]; 
     [self.view addSubview:[_arrayWithViews objectAtIndex:i]]; 
    } 
} 

- (NSMutableArray*)arrayWithColors { 
    if (!_arrayWithColors){ 
     self.arrayWithColors = [[NSMutableArray alloc]initWithObjects:[UIColor blackColor],[UIColor orangeColor], [UIColor blueColor], [UIColor purpleColor], nil]; 
    } 
    return _arrayWithColors; 
} 

- (UIColor*)getColor:(NSUInteger)index { 
    UIColor* color = [UIColor whiteColor]; //default view color 
    if (index < self.arrayWithColors.count){ 
     color = [self.arrayWithColors objectAtIndex:index]; 
    } 
    return color; 
} 
+0

ありがとうございました! –

関連する問題