Set NSArray as a property of custom class

74 views Asked by At

I have created one sub class / custom class of UIView

Here is MultiColorView.h file.

#import <UIKit/UIKit.h>
@interface MultiColorView : UIView
@property (strong, nonatomic) NSArray *colors; // default is nil
@end

Here is MultiColorView.m file

#import "MultiColorView.h"

@implementation MultiColorView

- (instancetype)initWithColors:(NSArray *)colors {

     self = [super init];

     self.layer.cornerRadius = 10.0;
     self.clipsToBounds = TRUE;

     CGFloat yOrigin = 0;
     CGFloat heightStipe = self.frame.size.height/colors.count;

     for (int i=0; i<colors.count; i++) {

         UILabel *lblStripe = [[UILabel alloc] initWithFrame:CGRectMake(0, yOrigin, self.frame.size.width, heightStipe)];
         lblStripe.backgroundColor = (UIColor *)[colors objectAtIndex:i];
         lblStripe.clipsToBounds = TRUE;
         [self addSubview:lblStripe];

         yOrigin = yOrigin + heightStipe;
     }
     return self;
}

- (void)setColors:(NSArray *)colors {

     self.layer.cornerRadius = 10.0;
     self.clipsToBounds = TRUE;

     CGFloat yOrigin = 0;
     CGFloat heightStipe = self.frame.size.height/colors.count;

     for (int i=0; i<colors.count; i++) {

         UILabel *lblStripe = [[UILabel alloc] initWithFrame:CGRectMake(0, yOrigin, self.frame.size.width, heightStipe)];
         lblStripe.backgroundColor = (UIColor *)[colors objectAtIndex:i];
         lblStripe.clipsToBounds = TRUE;
        [self addSubview:lblStripe];

         yOrigin = yOrigin + heightStipe;
    }
}

@end

Now if I use like :

Create property wherever you need.

@property (nonatomic, retain) IBOutlet MultiColorView *coloredView;

Set colours

NSArray *arrColors = @[[UIColor whiteColor], [UIColor yellowColor], [UIColor orangeColor], [UIColor redColor], [UIColor blackColor]];
self.coloredView.colors = arrColors;  // Crash here

Then app is crashing with reason :

[MultiColorView setColors:] : Unrecognized selector sent by instance.

But if I use like :

MultiColorView *view2 = [[MultiColorView alloc] initWithColors:arrColors];
view2.frame = CGRectMake(20, 100, self.view.frame.size.width, self.view.frame.size.height/2);
[self.view addSubview:view2];

Then it is working fine. Please suggest what's wrong in code. Thanks.

0

There are 0 answers