使用UIButton Swift 2更改另一个类中变量的值

时间:2015-08-04 18:37:20

标签: swift class swift2

我有一个视图控制器(称为BackgroundViewController),它有几个按钮,每个按钮设置不同视图的背景颜色,我的主视图。 (刚才叫做ViewController,是的,我在一个月前开始这个项目,之前我知道我应该把它命名为更好的东西)。为此,我设置了一个类SoundboardBrain,我打算使用它来保存应用程序的大部分逻辑。这是迄今为止的课程:

var backgroundName = String()
init(){
backgroundName = "Image"}

func changeBackgroundName(background: String){
backgroundName = background}

现在,BackgroundViewController有点像设置窗格,用户可以在其中选择其中一个选项,并通过他检查的选项显示项目符号。这是其中一个按钮:

@IBAction func whiteButton(sender: AnyObject){
    whiteBullet.hidden = false
    imageBullet.hidden = true
}

//这里我调用我在SoundboardBrain中定义的changeBackground函数        SoundboardBrain.changeBackgroundName("White") //然后我打印出结果,我仍然得到" Image"无所谓!

所以我想知道的是如何使用UIButton或ViewController的另一个对象更改类中初始化的变量。

1 个答案:

答案 0 :(得分:0)

你应该将SoundBrain的实例保存在变量中,或者使用单例。您可以稍后初始化一个新的SoundBrain实例。

Singleton更适合主应用逻辑。例如:

class SoundboardBrain {
    static let shared = SoundboardBrain()

    var backgroundName = "Image"

    func changeBackgroundName(background: String) {
        backgroundName = background
    }

}

SoundboardBrain.shared.backgroundName
// now the property is "Image"

// in UIButton
SoundboardBrain.shared.changeBackgroundName("something")

SoundboardBrain.shared.backgroundName
// now it's "something"

示例是在Playground中进行的,但没关系。

相关问题