简体   繁体   中英

make public class between Today extension and ViewController in app

I'm trying to create Today app extension. I want to have one UIViewController for loading all data to app and use the same variables in this UIViewController for Today Extension and App. For Example: I have UILabel for TodayAppExtension and for app and I want to connect Label text like:
my_label.text = "hello"
to both UILabels ... I tried make public class for do it like example:

THIS IS CLASS FOR BOTH VIEWCONTROLLERS

import UIKit

public class 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) } 

}

How can I access to this self.pacificLabel.text from StoryBoard from App and StoryBoard from Extension ? Always when I'm trying to call function updateClock() from ViewController I get this:

fatal error: unexpectedly found nil while unwrapping an Optional value

You never created pacificLabel.

In your

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

You need to create a UILabel object.

The error you're getting is because you declared it as an optional that WILL exist when you use it. So you dont need to unwrap it. As such it expected pacificLabel to exist, which it didn't at the time you 'unwrapped it'.

Create the UILabel object inside viewDidLoad and it will work.

If the issue is that you have this label existing in your storyboard, you need to control-drag that object from the view class (the view in the storyboard) to the script to create a reference to that object.

从视图类中拖动

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM