How to programmatically change UIColor view

Well, this question comes through a friend, so it may be lost in translation ...

Basically, we need to change the color in the view. It seems to be stored in a format NSString, but use NSStringfor installation UIColordoes not seem to do anything. In other words, if it NSString colorcontains the value "redColor", then:

self.view.backgroundColor = color;  //does nothing

Disclaimer: We are Objective-C / iPhone-newbies.

+3
source share
5 answers

Try

self.view.backgroundColor = [UIColor redColor];

You can also specify RGB values, for example

self.view.backgroundColor = [UIColor colorWithRed:200/255.0 green:0/255.0 blue:67/255.0 alpha:1.0];

All the best.

+20
source

The color must be a UIColor object:

self.view.backgroundColor = [UIColor redColor];
+1
source

self.view.backgroundColor = [UIColor blueColor];

self.view.backgroundColor = [UIColor colorWithRed:180.0/256.0 green:180.0/256.0 blue:180.0/256.0 alpha:1.0];
0

,

[self.view setBackgroundColor:[UIColor redColor]];
0

The easiest way to add color programmatically is to use ColorLiteral .

Just add the ColorLiteral property, as shown in the example, Xcode will offer you a complete list of colors that you can select. The advantage of this is less code, add HEX or RGB values . You will also get recently used colors from the storyboard.

Example: self.view.backgroundColor = ColorLiteral enter image description here

0
source

Source: https://habr.com/ru/post/1738343/


All Articles