Search code examples
iosobjective-cuicolor

Stored UIColor as Strings in NSMutableArray but unable to display the colors


Below is my NSMutableArray:

NSMutableArray *bgColorArr = [NSMutableArray arrayWithObjects:
    @"[UIColor colorWithRed:0.90 green:0.22 blue:0.21 alpha:1.0]",
    @"[UIColor colorWithRed:0.26 green:0.63 blue:0.28 alpha:1.0]",
    @"[UIColor colorWithRed:0.85 green:0.11 blue:0.38 alpha:1.0]",
    @"[UIColor colorWithRed:0.12 green:0.53 blue:0.90 alpha:1.0]",
    @"[UIColor colorWithRed:0.96 green:0.49 blue:0.00 alpha:1.0]",
    nil];

I am storing UIColors as strings due to some reason. I know how to store UIColors in NSMutableArray but I need to store them as NSString due to my requirement. When I am trying to display the colors in cellForRowAtIndexPath by using below code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *simpleTableIdentifier = .............

    cell.bgView.backgroundColor = (UIColor *)[bgColorArr objectAtIndex:indexPath.row];

    return cell;
}

Below is the error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString CGColor]: unrecognized selector sent to instance

By looking at the above error we can say that the String is not converting to UIColor. Is there any way to display the UIColor even though stored as a String? Any help will be really appreciated.


Solution

  • You can store hex strings in your array and then init UIColor with it.

    Here are some links that you might find useful to work with hex strings.

    How to use hex colour values

    How can I create a UIColor from a hex string?