Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Greg Stone
Greg Stone
2,705 Points

How does randomColor know to match text and background?

How does the system know to match the randomColor on the text and the background together rather than 2 separate colors randomly sifting through?

For instance, what if I wanted to the button text to display a completely different random color than the background?

I honestly have no clue what programming in iOS is like, however I use randomColor daily using languages I know (which is why this is a comment and not an answer. So basically this might be entirely incorrect and it might make no sense, but I hope it (at least) might help... If you were using a variable and setting its value as the randomColor, it will get one value (which is that one random color that was generated). If you use the same variable for both the text and backgroun color, the same color will be used (not sure). Of course that is in case you are using variables.

If not, I have no clue at all regarding what to tell you and I am sorry if my comment was useless lol ( there is a 99.9% chance it is) :)

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Greg,

I assume you're talking about storing a random color in a constant called randomColor. For example:

let randomColor = generateRandomColor()
// randomColor now stores something like RGB(120, 75, 75)

someView.backgroundColor = randomColor // RGB(120, 75, 75)
someLabel.textColor = randomColor // RGB(120, 75, 75)

Presumably we used a function like generateRandomColor() to get a random color, but once we store it in a constant, it's that value forever. We can use it however we want.

If you wanted two different random colors (can't guarantee they'll be different!), you'd use the function twice:

let firstRandomColor = generateRandomColor()
// firstRandomColor now stores something like RGB(140, 152, 6)

let secondRandomColor = generateRandomColor()
// secondRandomColor now stores something like RGB(36, 113, 97)

someView.backgroundColor = firstRandomColor  // RGB(140, 152, 6)
someLabel.textColor = secondRandomColor // RGB(36, 113, 97)

Let me know if that makes sense!

Cheers :beers:

-Greg