0

我创建了一个子类/自定义类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

然后应用程序崩溃的原因:

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

然后它工作正常。请提出代码中的问题。谢谢。

4

0 回答 0