自定义视图的随机颜色,无法重复使用

时间:2014-05-07 14:05:12

标签: ios objective-c uiview uicolor

我有一个自定义视图,这是一个圆形视图。该视图具有来自其他方法的自定义UIColor randomColor背景。

问题 - 我要做的只是使用一次颜色。在这种情况下,我有三个圆视图和6种颜色。所以我正在为三个圆视图中的每一个寻找一种颜色(随机选择)。完成的最佳方法是什么?

-(void)setupView {
    self.translatesAutoresizingMaskIntoConstraints = NO;
    float newRadius = self.frame.size.width/2;
    self.layer.cornerRadius = newRadius; 
    self.layer.masksToBounds= YES;

    self.layer.borderWidth = 5;
    self.layer.borderColor = [UIColor colorWithRed:0.138 green:0.225 blue:1.000 alpha:1.000].CGColor;


    self.backgroundColor = [self randomColor];

    [self setupLabel];
}


-(UIColor *)randomColor {
    static NSArray *__colors = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __colors = @[
                     [UIColor colorWithRed:.11372549  green:.819607843 blue:.819607843 alpha:1.0], //29,209,99
                     [UIColor colorWithRed:.882352941 green:.466666667 blue:.709803922 alpha:1.0], //225,119,181
                     [UIColor colorWithRed:.647058824 green:.164705882 blue:.482352941 alpha:1.0], //165,42,123
                     [UIColor colorWithRed:.482352941 green:.17254902  blue:.733333333 alpha:1.0], //123,44,187
                     [UIColor colorWithRed:.219607843 green:.098039216 blue:.698039216 alpha:1.0], //56,25,178
                     [UIColor colorWithRed:.678431373 green:.843137255 blue:.274509804 alpha:1.0]  //173,215,70
                     ];
    });
    int index = arc4random_uniform((uint32_t)__colors.count);
    return __colors[index];
}

2 个答案:

答案 0 :(得分:2)

Okey,如果要避免重复,则需要从数组中删除颜色(如果已选中) 试试这个:

-(UIColor *)randomColor {
    static NSMutableArray *__colors = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __colors = [NSMutableArray arrayWithArray:@[[UIColor colorWithRed:.11372549  green:.819607843 blue:.819607843 alpha:1.0], //29,209,99
                                                    [UIColor colorWithRed:.882352941 green:.466666667 blue:.709803922 alpha:1.0], //225,119,181
                                                    [UIColor colorWithRed:.647058824 green:.164705882 blue:.482352941 alpha:1.0], //165,42,123
                                                    [UIColor colorWithRed:.482352941 green:.17254902  blue:.733333333 alpha:1.0], //123,44,187
                                                    [UIColor colorWithRed:.219607843 green:.098039216 blue:.698039216 alpha:1.0], //56,25,178
                                                    [UIColor colorWithRed:.678431373 green:.843137255 blue:.274509804 alpha:1.0]  //173,215,70
                                                    ]];
    });
    int index = arc4random_uniform((uint32_t)__colors.count);

    UIColor *color = __colors[index];
    [__colors removeObjectAtIndex:index];
    return color;
}

答案 1 :(得分:1)

尝试在NSMutableArray中保存颜色,如果使用此颜色,则从数组中删除它:

[mutableArray removeObject:color];