0

I want to make a button that makes the background switch between red and green but I get this error:

missing return in a function expected to return UIView

I'm pretty new to coding, I've googled a bit but I didn't find anything.

Language:Swift

my code:

var timeLeft = 0
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    var buttonColor: UIView! {

        timeLeft = 1
    }

    func update() {
        if timeLeft > 0 {
            view.backgroundColor = UIColor.greenColor()
        }
        else {

            view.backgroundColor = UIColor.redColor()
        }
        timeLeft = timeLeft - 1

    }
}

thanks for helping

1

3 Answers 3

2

You declare buttonColor as a computed property which in its body requires you to return a UIView instance (since its type is UIView).

Read here or here about computed property and make sure it fits your needs as posted in your case

Sign up to request clarification or add additional context in comments.

Comments

0

Hi and welcome to stackoverflow

Remember to make an action connecting your UIButton to the code. Otherwise your code will not run when you click on the button. Also, consider using a Bool (true/false) variable to keep track of the background color.

Try the following code (remember to connect the 'click'-function to the button via the storyboard):

import UIKit

class ViewController: UIViewController {

    var isGreen = true

    @IBAction func click() {
        if isGreen {
            view.backgroundColor = UIColor.redColor()
            isGreen = false
        } else {
            view.backgroundColor = UIColor.greenColor()
            isGreen = true
        }
    }
}

Comments

0

var buttonColor: UIView! { get() { return (Object of UIView) } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.