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!

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


Simen Anthonsen
Simen Anthonsen
1,097 Points

Change color of UIView for 2 seconds

I want to create a function that turns my UIView green for a couple of seconds then after 2 seconds it gets turn to .None colour.

Do I need to use an NSTimer or is there something simpler?

1 Answer

Michael Hulet
Michael Hulet
47,908 Points

NSTimer seems to be your best bet. Here's a solution for Swift 2.2, which you can paste into your view controller:

@objc toggleViewColor() -> Void{
    <# Your view variable #>.backgroundColor = <# Your view variable #>.backgroundColor == UIColor.greenColor() ? UIColor.whiteColor() : UIColor.greenColor()

let timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(<# Your class name #>.toggleViewColor), userInfo: nil, repeats: true)