【发布时间】:2020-05-08 14:57:06
【问题描述】:
该程序设计为在按下按钮时让屏幕在黑白之间切换。问题是这应该通过按钮而不是开关来完成。这段代码有什么问题?当我运行程序时,背景不会切换。有关如何解决此问题的任何建议?
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
}
}
}
【问题讨论】:
-
您是否检查了那些 IBOutlet 和 IBAction 是否正确连接到情节提要?
-
我相信是这样,但我该如何检查
-
只需从情节提要中删除连接并重新连接(控制+鼠标拖动)。
-
颜色比较是一个非常糟糕的主意。删除
if backgroundView.backgroundColor == .white并维护一个 Bool 并检查并切换它。事实的来源应该是您的数据状态,而不是界面的某些瞬时质量。
标签: ios uiviewcontroller