将NSArray设置为自定义类的属性

时间:2018-06-07 11:39:37

标签: properties nsarray custom-controls xcode9.3 ios11.3

我创建了一个UIView

的子类/自定义类

这是MultiColorView.h档案。

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

这是MultiColorView.m档案

#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

现在,如果我使用:

在您需要的任何地方创建属性。

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

设置颜色

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

然后app因为原因而崩溃:

  

[MultiColorView setColors:]:实例发送的无法识别的选择器。

但如果我使用:

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];

然后它工作正常。请说明代码中的错误。 感谢。

0 个答案:

没有答案