I'm trying to create a header which is common for all UIViewControllers. So i have created a ParentViewController class sub classed from UIViewController which is having one UIButton and UILabel in header view.
And I have created a subclass ChildViewController from ParentViewController class. But in ChildViewController UIButton and UILabel are coming as nil.
I have created UIButton and UILabel in storyboard and connected outlet too.
Also I have changed ChildViewController super class to ParentViewController in storyboard. I'm struck.
I'm using below code.
Parent view controller
import UIKit
class ParentViewController: UIViewController {
#IBOutlet weak var viewTitle: UILabel!
#IBOutlet weak var menuButton : UIButton!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Child view controller
import UIKit
class ChildViewController: ParentViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.viewTitle.text = "String"
}
}
viewTitle coming as nil.
it's giving ("init(coder:) has not been implemented") error. can anyone help me?
Related
I am trying to create a subclass of UIViewController and then through the storyboard or programmatically pass data to it. What I have tried so far is to have a subViewController swift file with a class subViewController that is a UIViewController
import UIKit
class subViewController: UIViewController {
var s1 = String()
init(myString: String) {
self.s1 = myString
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(self.s1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
then in Identity Inspector I connect this to the view controller
and in AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let SubVC = subViewController(myString: "Komic")
self.window?.rootViewController = SubVC
self.window?.makeKeyAndVisible()
return true
}
This loads a black screen but it logs out myString. As far as I understand it doesn't create the view but it just creates the instance of the class and that's why it's giving me the black screen. I also know that this part
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
runs when the storyboard gives you the view. But I can't pass data in there that's why I am trying to do this programmaticaly. Is it possible somehow to do that? I know I could instantiateWithIdentifier with the storyboard but I can't find a way to pass my data through that....any help?
An (ugly) way to solve this issue:
You can set your var s1 from an external buffer in your code (AppDelegate variable in this example)
required init?(coder aDecoder: NSCoder) {
self.s1 = UIApplication.shared().delegate.bufferForS1
super.init(coder: aDecoder)
}
And when you initiate your UIViewController through Storyboard:
UIApplication.shared().delegate.bufferForS1 = myS1Value
self.navigationController!.pushViewControllerFading(self.storyboard!.instantiateViewController(withIdentifier: "myViewControllerID") as UIViewController)
You are not loading the view controller from the storyboard when you call your custom initialiser, if you create a customer initialiser it is your responsibility to create the view hierarchy programatically - typically in loadView() although lots of people do it in viewDidLoad().
In Order to the load the view hierarchy you defined in the storyboard you can do this:
let storyBoard = UIStoryboard(name: "storyboardName", bundle: NSBundle.mainBundle())
let viewController = storyBoard.instantiateViewControllerWithIdentifier("storyboardId")
You define the storyboard Id of a view controller in the identity inspector
I have a IBOutlet of a NSToolBar button in my NSWindowController class, which is my main window class:
class MainWindowController: NSWindowController {
#IBOutlet weak var myButton: NSButton!
// ...
}
I have a class MainViewController that is that content NSViewController of the main window.
How can I access this button in my content NSViewController? Is there a better way to organize the IBOutlets and the controllers to facilitate this access?
To access NSViewController from NSWindowController:
let viewController:MainViewController = self.window!.contentViewController as! MainViewController
To access NSWindowController from NSViewController:
let windowController:MainWindowController = self.view.window?.windowController as! MainWindowController
How about like this using delegate? This example will change your button's title.
#objc protocol SomeDelegate {
func changeTitle(title: String)
}
class ViewController: NSViewController {
weak var delegate: SomeDelegate?
#IBAction func myAction(sender: AnyObject) {
delegate?.changeTitle("NewTitle")
}
}
class MainWindowController: NSWindowController, SomeDelegate {
#IBOutlet weak var myButton: NSButton!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
let myVc = window!.contentViewController as! ViewController
myVc.delegate = self
}
func changeTitle(title: String) {
myButton.title = title
}
}
I am trying to make a SystemStatusBar popover for Mac. (Roughly, translating this Cocoa app to a Swift app). However, the view that I am using never shows up and the popup appears in the bottom left of the screen replicating the StatusBarItem.
This is what I expect (and that happens in the example from case of example from the link):
and this is what actually shows up (in my, Swift version of the application) instead of the NSPopover being shown in the StatusBar [Showing or Hiding the popup is controlled by the two buttons as shown in the previous figure. In this screenshot I have not added that window as it remains the same.]:
This is the AppDelegate:
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
var statusView : StatusView!
var popController: PopViewController!
#IBAction func showPop(sender: NSButton)
{
statusView.showPopup()
}
#IBAction func hidePop(sender: NSButton)
{
statusView.hidePopup()
}
func applicationDidFinishLaunching(aNotification: NSNotification)
{
var height = NSStatusBar.systemStatusBar().thickness
statusView = StatusView(frame: NSMakeRect(0, 0, CGFloat(height), CGFloat(height)))
}
}
The CustomView:
class StatusView : NSView, NSMenuDelegate
{
var imageView: NSImageView!
var statusItem: NSStatusItem!
var popover: NSPopover!
var popController: PopViewController!
required init? (coder: NSCoder)
{
super.init(coder: coder)
}
override init(frame frameRect: NSRect)
{
var height = NSStatusBar.systemStatusBar().thickness
imageView = NSImageView(frame: NSMakeRect(0, 0, CGFloat(height), CGFloat(height)))
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(CGFloat(height))
super.init(frame: frameRect)
imageView.image = NSImage(named: "mf-image-black.png")
self.addSubview(imageView)
statusItem.view = self
popover = NSPopover()
popController = PopViewController(nibName: "PopViewController", bundle: nil)
popController.view = self
popover.contentViewController = popController
}
func showPopup()
{
if(!popover.shown)
{
popover.showRelativeToRect(self.frame, ofView: self, preferredEdge: NSMinYEdge)
}
}
func hidePopup()
{
if(popover.shown)
{
popover.close()
}
}
}
and the ViewController:
class PopViewController: NSViewController
{
#IBOutlet var statusView: StatusView!
override init?(nibName: String?, bundle: NSBundle?) {
super.init(nibName: nibName, bundle: bundle)
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
}
I am not exactly sure what is that I am missing here. The StatusItem never seems to make use of the PopViewController nib.
NSViewController, when instantiated from storyboards under Swift, seems to have a reference cycle somewhere.
Calling the following code multiple times will instantiate and set a new view controller, but the old view controller is never dealloced. In the code, containerViewController is an NSViewController which should contain a single NSViewController, containerView is a subview within containerViewController, and identifier is the storyboard identifier to instantiate.
// Remove any sub viewcontrollers and their views
for viewController in containerViewController.childViewControllers as [NSViewController] {
viewController.view.removeFromSuperview()
viewController.removeFromParentViewController()
}
// Create and set up the new view controller and view.
let viewController = storyboard!.instantiateControllerWithIdentifier(identifier) as NSViewController
let view = viewController.view
view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(viewController.view)
containerViewController.addChildViewController(viewController)
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: nil, metrics: nil, views: ["view": view]))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: nil, metrics: nil, views: ["view": view]))
(Sample project no longer available)
I used an Apple TSI and they agree it's a bug, which I have filed, but I expected someone else to have come up against this by now seeing as NSViewControllers and storyboards are now the de facto on OSX. How have you worked around this problem? Or does it not affect anyone else and I am doing something wrong?
Pre-bounty edit: Each view controller must be able to link to any other view controller from code as the destination is determined on the fly. This seems to remove segues as an option.
Bug fixed
As of Xcode 6.3 this is no longer a bug.
Another answer.
It seems, only the segues defined on Storyboard can perform view controller deallocation.
So, Here is a very ugly but working workaround.
class DismissSegue: NSStoryboardSegue {
var nextViewControllerIdentifier:String?
override func perform() {
let src = self.sourceController as NSViewController
let windowController = src.view.window!.windowController() as TopLevelWindowController
src.view.removeFromSuperview()
src.removeFromParentViewController()
if let identifier = nextViewControllerIdentifier {
windowController.setNewViewController(identifier)
}
}
}
class TopLevelWindowController: NSWindowController {
var containerView: NSView!
var containerViewController: ContainerViewController! {
didSet {
setNewViewController("FirstView")
}
}
func setNewViewController(identifier: String) {
// Create and set up the new view controller and view.
let viewController = storyboard!.instantiateControllerWithIdentifier(identifier) as NSViewController
let view = viewController.view
view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(viewController.view)
containerViewController.addChildViewController(viewController)
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: nil, metrics: nil, views: ["view": view]))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: nil, metrics: nil, views: ["view": view]))
}
}
class ContainerViewController: NSViewController {
#IBOutlet var containerView: NSView!
override func viewDidAppear() {
super.viewDidAppear()
if let window = view.window {
if let topLevelWindowController = window.windowController() as? TopLevelWindowController {
topLevelWindowController.containerView = containerView
topLevelWindowController.containerViewController = self
}
}
}
}
class FirstViewController: NSViewController {
required init?(coder: NSCoder) {
super.init(coder: coder)
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("First VC init at \(pointerAddress)")
}
deinit {
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("First VC de-init at \(pointerAddress)")
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if let segue = segue as? DismissSegue {
segue.nextViewControllerIdentifier = "SecondView"
}
}
}
class SecondViewController: NSViewController {
required init?(coder: NSCoder) {
super.init(coder: coder)
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("Second VC init at \(pointerAddress)")
}
deinit {
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("Second VC de-init at \(pointerAddress)")
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if let segue = segue as? DismissSegue {
segue.nextViewControllerIdentifier = "FirstView"
}
}
}
Procedure for modifying your Storyboard:
Disconnect #IBAction from buttons.
Create "DUMMY" view controller scene with normal NSViewController.
Connect custom segues from buttons to "DUMMY".
Configure these segue as shown.
Please let me know if this solution doesn't meet your demand.
This might not solve your problem, but the only workaround I found is:
Embed initial view controller using "Container View"
No #IBAction
Use custom NSStoryboardSegue to Switch between view controllers.
Something like this:
import Cocoa
class TopLevelWindowController: NSWindowController {
}
class ContainerViewController: NSViewController {
}
class FirstViewController: NSViewController {
required init?(coder: NSCoder) {
super.init(coder: coder)
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("First VC init at \(pointerAddress)")
}
deinit {
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("First VC de-init at \(pointerAddress)")
}
}
class SecondViewController: NSViewController {
required init?(coder: NSCoder) {
super.init(coder: coder)
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("Second VC init at \(pointerAddress)")
}
deinit {
let pointerAddress = NSString(format: "%p", unsafeBitCast(self, Int.self))
NSLog("Second VC de-init at \(pointerAddress)")
}
}
class MySegue: NSStoryboardSegue {
override func perform() {
let source = self.sourceController as NSViewController
let destination = self.destinationController as NSViewController
if let containerViewController = source.parentViewController {
source.view.removeFromSuperview()
source.removeFromParentViewController()
let view = destination.view
let containerView = containerViewController.view
view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(view)
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: nil, metrics: nil, views: ["view": view]))
containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: nil, metrics: nil, views: ["view": view]))
containerViewController.addChildViewController(destination)
}
}
}
I'm having problems implementing a subclass to NSView that implements NSCoding.
It seems like the declarations of init(coder: NSCoder) are conflicting in NSView and NSCoding.
NSView nowadays says it's failable, but NSCoding still says it's non-failable.
When I try to override init(coder: NSCoder) and do my custom initialisation, Xcode 6.1 gives me an error message:
A non-failable initializer cannot chain to failable initializer
'init(coder:)' written with 'init?'
How am I supposed to do my custom init of my class?
Here's a silly example where I extend a view and I want to persist an additional click counter for my view.
import Cocoa
import Foundation
class MyView: NSView, NSCoding {
var clickCounter:Int = 0
required init(coder: NSCoder) {
super.init(coder: coder)
coder.encodeObject(self.clickCounter,
forKey: "clickCounter")
}
override func encodeWithCoder(coder: NSCoder) {
super.encodeWithCoder(coder)
coder.encodeObject(self.clickCounter, forKey: "clickCounter")
}
override func mouseDown(theEvent: NSEvent) {
clickCounter++
}
}
You don't have to explicitly conform to NSCoding, because NSResponder (superclass of NSView) already conforms to it.
required init?(coder: NSCoder) {
super.init(coder: coder)
self.clickCounter = coder.decodeObjectForKey("clickCounter") as Int
}