使用单个按钮Xcode或swift切换视图控制器的背景颜色



程序设计为按下按钮时屏幕在黑色和白色之间切换。问题是,这应该用一个按钮而不是开关来完成。这个代码出了什么问题?当我运行程序时,背景不会切换。关于如何解决这个问题,有什么建议吗?

import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// set the background color to white when opened
backgroundView.backgroundColor = .white
}
@IBOutlet weak var OnOffButton: UIButton!
@IBOutlet var backgroundView: UIView!
@IBAction func OnOff(_ sender: AnyObject) {
// write your code here
// code should change background color to black if it is white and vice versa. 
if backgroundView.backgroundColor == .white {
backgroundView.backgroundColor = .black
} else {
backgroundView.backgroundColor = .white
}
}
}

我刚刚创建了一个全新的单视图iOS应用程序,它运行得很好。

在新项目中,我在故事板的第一个场景中添加了一个UIButton,并将其连接到OnOff:

注意:顺便说一下,函数的开头不应该用大写字母。它应该是onOff:。使用Refactor可以更改此设置。

然后,我将一个UIView拖动到该场景,右键单击视图并添加一个New Referencing Outlet,从+向右拖动到左侧的View Controller文本,并将其指定给backgroundView

它第一次尝试就跑得很好。您可能将IBOutlet或IBAction接线错误。在OnOff:函数中添加一个断点,看看单击按钮时是否触发了它。如果是,请在控制台中输入以下内容,确保backgroundView的IBOutlet已正确连接:

po self.backgroundView

如果它是nil,那么它没有正确连接到UIView。

祝你好运!

最新更新