簡體   English   中英

在應用程序中的Today擴展和ViewController之間公開類

[英]make public class between Today extension and ViewController in app

我正在嘗試創建Today應用擴展。 我想要一個UIViewController來將所有數據加載到應用程序,並在該UIViewController中為Today Extension和App使用相同的變量。 例如:我有用於TodayAppExtension和app的UILabel,我想連接Label文本,例如:
my_label.text =“你好”
到兩個UILabel ...我嘗試使它成為公共類,例如:

這是兩個視圖控制器的類

導入UIKit

公共類AppDataViewController:UIViewController {

 @IBOutlet public var pacificLabel: UILabel! override public func viewDidLoad() { super.viewDidLoad() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public func updateClocks() { var time: NSDate = NSDate() println("Time: \\(time)") var timeString : NSString = "Time: \\(time)" let formatter:NSDateFormatter = NSDateFormatter(); var timeZone = NSTimeZone(name: "UTC") formatter.timeZone = timeZone formatter.dateFormat = "HH:mm:ss" println("UTC Time: \\(formatter.stringFromDate(time))") timeZone = NSTimeZone(name: "US/Pacific") formatter.timeZone = timeZone formatter.dateFormat = "HH:mm:ss" println("PST Time: \\(formatter.stringFromDate(time))") self.pacificLabel.text = formatter.stringFromDate(time) } 

}

如何從App的StoryBoard和Extension的StoryBoard訪問此self.pacificLabel.text? 總是在嘗試從ViewController調用函數updateClock()時得到此信息:

致命錯誤:解開Optional值時意外發現nil

您從未創建過pacificLabel。

在你的

override public func viewDidLoad() {
    super.viewDidLoad()
}

您需要創建一個UILabel對象。

您收到的錯誤是因為您在使用它時將其聲明為WILL存在的可選內容。 因此,您無需拆開包裝。 因此,它希望pacificLabel存在,而在您“解開它”時並沒有。

在viewDidLoad內部創建UILabel對象,它將起作用。

如果問題是情節提要中存在此標簽,則需要控制該對象從視圖類(情節提要中的視圖)到腳本的拖拽,以創建對該對象的引用。

從視圖類中拖動

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM