[英]Changing Label's Text From a PopOver
I have a main view which has a label named timeLabel and a button that calls a popover view. 我有一个主视图,其中有一个名为timeLabel的标签和一个调用弹出窗口的按钮。
In the popover view I can choose a time (hour and min), when I choose I want the label text to immediately changes to the selected hour (the label has an initial value : "22:00"). 在弹出视图中,我可以选择一个时间(小时和分钟),当我选择时,我希望标签文本立即更改为选定的小时(标签的初始值为“ 22:00”)。
What I tried to do is create a function in the main view that changes the label's text: 我试图做的是在主视图中创建一个函数来更改标签的文本:
func setNotiTimeHour(hour: Int)
var time = self.notiTimeLabel.text!.componentsSeparatedByString(":") //ERROR
var newTime = String(hour) + ":" + time[1]
self.notiTimeLabel.text = newTime
}
func setNotiTimeMin(min: Int) {
var time = self.notiTimeLabel.text!.componentsSeparatedByString(":") //ERROR
var newTime = time[0] + ":" + String(min)
self.notiTimeLabel.text = newTime
}
And then I tried to calls these functions when the hour or minute is changes like this: 然后,当小时或分钟发生如下变化时,我尝试调用这些函数:
SettingsTableViewController().setNotiTimeHour(Int(hours))
SettingsTableViewController().setNotiTimeHour(Int(minutes))
When I call the function like this I get an error that says: "fatal error: unexpectedly found nil while unwrapping an Optional value" 当我这样调用函数时,出现错误消息:“致命错误:在展开可选值时意外发现nil”
I think it means the label has no value. 我认为这意味着标签没有价值。
Why do I get this error, is there another way to change the label's text? 为什么会出现此错误,还有另一种方法来更改标签的文本吗?
SettingsTableViewController()
creates a new view controller. SettingsTableViewController()
创建一个新的视图控制器。 It does not use the instance you already have. 它不使用您已有的实例。 That's why the label is
nil
. 这就是标签为
nil
的原因。
You need to hand your popover controller a reference to the existing view controller, save it in a property, and then call that one. 您需要为您的popover控制器提供对现有视图控制器的引用,将其保存在一个属性中,然后调用该属性。 You may want to create a delegate protocol for this so this popover class can be presented from other view controllers besides
SettingsTableViewController
. 您可能要为此创建一个委托协议,以便可以从
SettingsTableViewController
之外的其他视图控制器中呈现此弹出类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.