我需要一个来自全局范围的函数来更改故事板上的标签。
当我尝试运行此代码时,我得到的错误是:
fatal error: unexpectedly found nil while unwrapping an Optional value
问题是viewController.congratulations为null。
如何解决这个问题?提前谢谢!
func myAlert ()
{
// how to change 'configuration.text' from here?
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewController : ViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController;
viewController.congratulations.text = "test";
}
class ViewController: UIViewController
{
@IBOutlet weak var congratulations: UILabel!;
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myAlert();
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:1)
您不应直接尝试从定义它的类外部访问UILabel
。只有在viewDidLoad
子类的特定实例上调用UIViewController
时才会创建标签。
您应该做的是将您想要在标签上显示的文字存储在另一个变量中,并在课堂外更改该变量。
答案 1 :(得分:0)
名为congratulations
的IBOutlet在viewDidLoad
中为零。因此,在String
(比如stringValue)创建一个ViewController
属性。导航时设置该字符串属性
在viewController的viewDidLoad方法中,获取stringValue并将其值设置为label
self.congratulations.text = stringValue;
答案 2 :(得分:0)
将myAlert()添加到ViewController类中解决了这个问题。
class ViewController: UIViewController
{
func myAlert ()
{
self.congratulations.text = "vrebreberbfrbb";
}
@IBOutlet weak var congratulations: UILabel!;
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myAlert();
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}