Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,019 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