【问题标题】:Switching the background color of view controller using a single button Xcode or swift使用单个按钮 Xcode 或 swift 切换视图控制器的背景颜色
【发布时间】: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


【解决方案1】:

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

在新项目中,我在情节提要的第一个场景中添加了一个 UIButton 并将其连接到 OnOff:

注意:顺便说一下,您不应该以大写字母开头函数。应该是onOff:。使用重构来改变这一点。

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

第一次尝试就完美运行。您可能错误地连接了 IBOutlet 或 IBAction。在OnOff: 函数中添加一个断点,看看当你点击按钮时它是否被触发。如果是,请通过在控制台中输入以下内容来确保 backgroundView 的 IBOutlet 已正确连接:

po self.backgroundView

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

祝你好运!

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 2021-03-28
    • 2020-09-14
    • 1970-01-01
    • 2020-12-17
    • 2011-03-05
    • 2021-04-27
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多