简体   繁体   English

在预期会迅速返回的函数中缺少返回

[英]missing return in a function expected to return swift

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 预期返回UIView的函数中缺少返回

I'm pretty new to coding, I've googled a bit but I didn't find anything. 我对编码还很陌生,我已经在Google上搜索了一下,但没有找到任何东西。

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 谢谢你的帮助

You declare buttonColor as a computed property which in its body requires you to return a UIView instance (since its type is UIView ). 您将buttonColor声明为计算属性,该属性在其主体中要求您返回UIView实例(因为其类型为UIView )。

Read here or here about computed property and make sure it fits your needs as posted in your case 在此处此处阅读有关计算属性的信息,并确保其符合您的情况(如您所见)

Hi and welcome to stackoverflow 嗨,欢迎来到stackoverflow

Remember to make an action connecting your UIButton to the code. 请记住执行将UIButton连接到代码的操作。 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. 另外,请考虑使用布尔(true / false)变量来跟踪背景颜色。

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
        }
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM