【问题标题】:How to change the color of a UIlabel in the next ViewController, to the selected color in the current ViewController in Swift如何将下一个 ViewController 中的 UIlabel 的颜色更改为 Swift 中当前 ViewController 中的选定颜色
【发布时间】:2016-02-29 15:47:49
【问题描述】:

我有两个视图控制器。在第一个中,我有标签和代表一种颜色的 4 个按钮,以及一个名为 next 的按钮。我想实现这一点,当用户在第一个视图控制器中选择一种颜色并单击下一步时,我的下一个视图控制器中的标签将自动具有该颜色。

这是我目前所拥有的,但我无法让它发挥作用。

import UIKit

class ViewController: UIViewController {

var backGroundColor = UIColor()

@IBOutlet var face: UILabel!


@IBAction func red(sender: AnyObject) {

    face.backgroundColor = UIColor.redColor()
}

@IBAction func green(sender: AnyObject) {

    face.backgroundColor = UIColor.greenColor()

}

@IBAction func blue(sender: AnyObject) {

    face.backgroundColor = UIColor.blueColor()

}

@IBAction func yellow(sender: AnyObject) {

    face.backgroundColor = UIColor.yellowColor()

}

@IBAction func next(sender: AnyObject) {


    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("face") as! Face2

     vc.newFace.backgroundColor =  self.face.backgroundColor

    self.navigationController?.pushViewController(vc, animated: true)
}

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

}

// My Face2 class:
import UIKit

class Face2: UIViewController {

    var backGroundColor = UIColor()


    @IBOutlet var newFace: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

//    var  vc = ViewController()
        self.newFace.backgroundColor = backGroundColor


    }

}

【问题讨论】:

  • vc2的目的是什么?

标签: ios swift uilabel


【解决方案1】:

欢迎来到 SO。

你犯了一个常见的设计错误。

不要试图直接操作第二个视图控制器的视图。那是糟糕的设计,而且通常不起作用。

改为向您的 Face2 类添加一个/多个属性。

在这种情况下,backgroundColor 属性可能就足够了。

next 函数中设置该属性,然后在 Face2 类的 viewDidLoad 方法中,使用颜色来设置需要使用自定义颜色的任何视图的背景颜色。如果您稍后决定需要更改颜色的视图集不同,则可以更改 Face2 类的代码,而第一个视图控制器根本不需要更改。

您还需要摆脱 vc2。这是没有意义的。你创建一个新的 Face2 视图控制器 vc 并调用 instantiateViewControllerWithIdentifier。那是您应该配置的那个。您在 vc2 中创建的那个永远不会用于任何事情。一旦你退出 next() 函数,它就会被释放。

【讨论】:

  • 您好,Duncan,感谢您的回答和对我的欢迎。我仍在学习 Swift,我的目的是学习避免糟糕的设计。我在上面编辑了我的代码,以显示我根据您的建议所做的更改。不幸的是,我仍然做错了什么,因为它在展开时崩溃了?可能我做错了什么。
  • 在我看来,您向 Face2 类添加了 backgroundColor 属性,但在发送视图控制器中,您仍然有代码尝试直接在 newFace 插座上设置颜色。不要那样做。请改用vc.backgroundColor = self.face.backgroundColor 行。
  • 嗨,Dunca,你太棒了,感谢您的帮助。它解决了我的问题。我连根拔起你的答案,但因为我是新人,我显然不能。再次感谢!
  • 在您获得至少 15 个代表之前,您不能投票,但如果我的回答解决了您的问题,您应该接受它。这告诉其他人这个答案解决了问题,这使得线程对其他人更有用。接受最早/最好的正确答案是在本网站提问的重要部分。
【解决方案2】:

我的建议是为第二个视图控制器设置一个 nsstring(按下颜色按钮时设置的字符串)属性,并在第二个视图控制器视图中加载基于传递的字符串进行切换以设置背景颜色

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-21
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2020-02-12
    • 2016-09-01
    相关资源
    最近更新 更多