Reuse identifier in nib does not match the identifier used to register the nib - xcode

I have a Framework/Module written in Swift which provides some custom controls with IBDesignable functionality.
Currently I am working on a control based on a CollectionView. The CollectionView and the custom CollectionViewCell are build in Nib files. To load the CollectionViewNib and add the Designable funcionality I use this NibDesignable class. After initalising the CollectionView I register the CollectionViewCell as following:
let cellIdentifier = "collectionViewCell"
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
private func setup() {
let bundle = NSBundle(forClass: self.dynamicType)
self.collectionView.registerNib(UINib(nibName: "CollectionViewCell", bundle: bundle), forCellWithReuseIdentifier: self.cellIdentifier)
}
After adding my Framework as Embedded Binary to another app I can use my new custom CollectionView as expected, but unfortunately the Designable functionality isn´t working well, instead I get the following error message:
IB Designables: Failed to update auto layout status:
The agent raised a "NSInternalInconsistencyException" exception:
view reuse identifier in nib (ibCollectionViewCell) does not match the identifier used to register the nib (collectionViewCell)
As describe above my Control works in the Simulator and on my Phone, so no I don´t use different identifiers. I don´t know where XCode gets this
ibCollectionViewCell identifier, but when I use it as identifier for my CollectionViewCell every thing works like a charm.
Any ideas where this identifier comes from and why XCode can´t load my custom CollectionViewCell with my own identifier?

After updating from XCode 7 Beta 4 to Beta 5 the error was gone. So I assume there was something buggy in the previous version

Related

Swift Loading a View from a XIB

I have been following this tutorial in order to load a xib at the push of a button in a view controller:
http://www.thomashanning.com/loading-a-view-from-a-xib/
At this line:
if let customView = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil).first as? CustomView {
I get the below error:
Use of undeclared type 'CustomView'
I have followed the tutorial every step several times and I do not know what I am missing. Can anybody help with an idea of what could be wrong?
The error indicate that you missed a step declaring the class
Use of undeclared type 'CustomView'
One of few things could be missed:
You didn't create the CustomView.swift file, the tutorial skipped this part. That file should contine the following:
import UIKit
class CustomView: UIView {
#IBAction func ButtonDidPressed(sender: AnyObject) {
print("Button Pressed")
}
}
Corresponding error (in editor):
Use of undeclared type 'CustomView'
In Storyboard Identity Inspector you didn't set the class name correctly.
Corresponding error (in run time):
Unknown class CustomView in Interface Builder file.
Your class declaration is not identical to the call, but I think you should be able to identify this situation in Xcode editor.
Corresponding error (in editor):
Use of undeclared type 'CustomView'
You can use this way give same name for UIView class and View/.Xib also
let alert = NSBundle.mainBundle().loadNibNamed("PromotionMenu", owner: nil, options: nil)[0] as? PromotionMenu
alert?.delegate = self
self.view.addSubview(alert!)
Thank you all for your detailed answers, unfortunately none of them were of help.
There was not anything logic in what was happening, as I was not able to create any new classes of any type and call them without error.
So after many hours of frustration I created a new project, dragged all my old files in it(except plist) and after a run I was able to create new classes and create instances of them without errors.

IBOutlet is nil, but it is connected in storyboard, Swift

Using Swift 1.1 and Xcode 6.2.
I have a UIStoryboard containing a singular, custom UIViewController subclass. On it, I have an #IBOutlet connection of type UIView from that controller to a UIView subclass on the storyboard. I also have similar outlets for subviews of that view. See figure A.
But at run time, these properties are nil (Figure B). Even though I have assured I've connected the outlets in Interface Builder.
Thoughts:
Is it possible that because I am using a subclass of a subclass something messes up with the initialization? I am not overriding any initializers
awakeFromNib: is not getting called for some reason
Maybe it doesn't connecting to subviews on subviews
Things I have tried:
Matching #IBOutlet and storyboard item types exactly (instead of UIView)
Deleting property and outlet and re-added them
Figure A*
Figure B
*The obscured code in Figure A is:
#IBOutlet private var annotationOptionsView: UIView!
#IBOutlet private var arrivingLeavingSwitch: UISegmentedControl!
Thank you.
Typically this happens because your view controller hasn't loaded its view hierarchy yet. A view controller only loads its view hierarchy when something sends it the view message. The system does this when it is time to actually put the view hierarchy on the screen, which happens after things like prepareForSegue:sender: and viewWillAppear: have returned.
Since your VC hasn't loaded its view hierarchy yet, your outlets are still nil.
You could force the VC to load its view hierarchy by saying _ = self.view.
Did you instantiate your view controller from a Storyboard or NIB, or did you instantiate it directly via an initializer?
If you instantiated your class directly with the initializer, the outlets won't be connected. Interface Builder creates customized instances of your classes and encodes those instances into NIBs and Storyboards for repeated decoding, it doesn't define the classes themselves. If this was your problem, you just need to change the code where you create your controller to instead use the methods on UIStoryboard, or UINib.
Have you tried running Product > Clean. Solved a very similar problem for me.
The storyboard wasn't recognizing any further UI things I added to it. At run time all the references were nil. So I cleared my derived data folder and then those connections worked again.
This happened for me because I was accidentally instantiating my view controller directly instead of instantiating it through the storyboard. If you instantiate directly via MyViewController() then the outlets won't be connected.
This was happening to me with my custom collection view cell. Turns out I had to replace my registerClassforReuseIdentifier method with registerNib. That fixed it for me.
In my case, it happened because I overriden the loadView method in my ViewController subclass, but forgot to add [super loadView]
-(void)loadView {
// blank
}
When you override the loadView method, the it is your responsibility to init your subviews. Since you override it, the views from interface builder do not get the chance to convert to cocoa objects and thus outlets remain nil.
If you implement loadView in your view controller subclass, then it becomes your responsibility load the UI elements from from storyboard/xib into code.
Or just call
[super loadView];
So that the superclass gets the chance to load storyboard/xib into code.
If you instantiate view controller through programmatically. Then
try creating it like below
let initialVC = self.storyboard?.instantiateViewController(withIdentifier: "InitialVC") as! InitialVC
instead of directly
let initialVC = InitialVC()
This worked for me.
You can call controller.view to force to load the view to initialize the IBOutlets, then you will be able to assign the values.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "identifier") {
let controller = segue.destinationViewController as! YourController
let _ = controller.view //force to load the view to initialize the IBOutlets
controller.your_IBOutlet_property = xxx
...
controller.delegate = self
}
}
I encounter this problem recently! Here is my thought.
The problem is not about you storyboard or any link issue. It is about how you initiate your ViewController. Especially when you are using Swift.(There is barely nothing in the editor when you create a class file)
By simply using the init() from super class can not initiate anything you worked with story board. So what you need to do is changing the initialisation of the ViewController. Replace
let XXViewController = XXViewController()
by
let XXViewController = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("XXViewController") as! XXViewController
This tells the program to go to the storyboard find XXViewController and initiates all IBOutlet in your storyboard.
Hope this help~ GL
For me, this occurred when I accidentally declared my view controller's class as
class XYZViewController: UINavigationController {
}
(ie as a UINavigationController not a UIViewController).
Xcode doesn't pick up on this mistake, the class seems to build fine, and override functions such as viewDidLoad, viewWillAppear, etc. all work correctly. But none of the IBOutlets get connected.
Changing the declaration to
class XYZViewController: UIViewController {
}
fixed it completely.
2019, ONE POSSIBILITY FOR THIS HORRIBLE PROBLEM:
Say you have perhaps a container view that shows some sort of clock. So you have
class Clock: UIViewController
You actually use it in a number of places in the app.
On the main screen, on the details screen, on the edit screen.
You have a complicated snapchat-like modern app.
In fact, Clock may actually be loaded more than once at the same time somewhere on the same screen. (Maybe it's hidden in some cases.)
You start working on one instance of Clock on one of your many storyboards.
On that storyboard you add a label, NewLabel.
Naturally you add the outlet in code. Everything should work. All the other outlets work perfectly.
You have definitely linked the outlet.
But the app crashes with NewLabel as nil.
Xcode clearly tells you "you forgot to connect the outlet".
The reason is this .......... you have "NewLabel" on only one of the storyboard uses of Clock!
The crash is actually from >>> an other place <<<< you are using Clock!!!!
Xcode does not tell you the crash is from another place altogether, not from where you are working!
The crash is actually not from the place you are working - it's from another storyboard, where there is no "NewLabel" item on that storyboard!!!
Frustrating.
For Swift 3.
func configureView() {
let _ = self.view
}
In my case, the app started crashing all of a sudden.
Debugging it revealed that all outlets were still nil at the time of viewDidLoad().
My app still uses nibs (not storyboards) for most view controllers. Everything was in place, all outlets wired properly. I double-checked.
We typically instantiate our view controllers as
let newVC = MYCustomViewController()
...which for some reason seems to work as long as the .xib is named the same as the view controller class (not sure how that works, though. We are not calling init(nibName:bundle:) with nil arguments, or overriding init() to do so on self like it is typically suggested...).
So I tried to explicitly call
let newVC = MYCustomViewController(nibName: "MYCustomViewController", bundle: .main)
...only to be greeted with the runtime exception error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/nicolasmiari/Library/Developer/CoreSimulator/Devices/3DA3CF21-108D-498F-9649-C4FC9E3C1A8D/data/Containers/Bundle/Application/C543DDC1-AE86-4D29-988C-9CCE89E23543/MyApp.app> (loaded)' with name 'MYCustomViewController''
And then, I saw it:
The "Target Membership" checkbox of the .xib file was unchecked.
Must have happened when resolving one of the frequent merge conflicts regarding the Xcode project file.
Apple definitely needs to come up with a project file format that is more SCM-friendly.
You need to load the view hierarchy first in order to instantiate the outlets in the storyboard. For this, you can manually call the loadView or loadViewIfNeeded methods.
100% Working solution for creating ViewControllers from XIB without StoryBoards
Create class CustomViewController : UIViewController
Create view CustomViewControllerView.xib
In CustomViewControllerView.xib in Interface Builder select Placeholders -> File's Owner
In "Attributes inspector" set Class to CustomViewController
In "Connections inspector" connect "view" to top-level view of xib (ensure top-level view's Class is not pointing to CustomViewController)
In "Connections inspector" connect other outlets (if needed/exist)
Create an instance of CustomViewController in parent view controller/App delegate
7.1.
// creating instance
let controller = CustomViewController()
7.2.
// connecting view/xib with controller instance
let bundle = Bundle(for: type(of: controller))
bundle.loadNibNamed("CustomViewControllerView", owner: controller, options: nil)
7.3.
// get/set outlets
controller.labelOutlet.text = "title"
controller.imageOutlet.image = UIImage(named: "image1")
Check your IBOutlet connection if it connected to the File owner or the view.
There could be mistakes.
Other case:
Your outlets won't get set until the view controller's view is actually instantiated, which in your case is probably happening shortly after initWithNibName:bundle:—at which point they'll still be nil. Any setup you do that involves those outlets should be happening in your view controller's -viewDidLoad method.
For me, I had same error on a localized storyboard, an element was added in some locale and not in the other, so I had null reference for that element when switched to the missing element locale, I had to remove (redundant) localization for that storyboard using https://stackoverflow.com/a/42256341/1356559.
For me, this was crashing because containerView was nil.
Here is my code with Crash.
#IBOutlet private var containerView: UIView! // Connected to Storyboard
override open func loadView() {
containerView.addSubview(anotherView)
}
The missing thing was calling the super.loadView(). So adding it solved problem for me.
Fixed Code:
#IBOutlet private var containerView: UIView!
override open func loadView() {
super.loadView()
containerView.addSubview(anotherView)
}
I had a similar issue when I had previously added register(_:forCellReuseIdentifier:) for the custom cell after I had already defined the identifier in the storyboard. Had this code in the viewDidLoad() function. Once I removed it, it worked fine.
Yet another case I just ran into. I changed the name of my class for the UIViewController, but I forgot to change the name of the .xib file where the interface was built.
Once I caught this and made the file names reflect the class name, it was all good!
I hope that helps someone.
Got one more ...
If you have a custom class for a UITableViewCell but forget to specify Custom in the Style of the cell.
Check to see if you have any missing or disconnected outlets.
You can validate if the is view is loaded.
if isViewLoaded && view.window != nil {
//self.annotationOptionsView.
}
select both .h and .m view controller files
remove the reference of those files
re-add the files to your project tree
open the storyboard, eventually re-build the project
Accidently I subclassed my view controller with AVPlayerViewController instead of UIViewController. By replaying it to UIViewController things back normal. This should help.
No build cleaning (normal&full), removing derived data folders and quitting Xcode worked for me.
I had the same problem after copying a class (linked to a xib) to reuse it with another viewcontroller class (linked to a storyboard).
I forgot to remove
override var nibName
and
override var nibBundle
methods.
After removing them, my outlets started to work.
I see you use ViewController!? in ViewController class you must use -viewDidLoad, not -awakeFromNib, -awakeFromNib use for UIView class
If you have two main.storyboards and you are making changes to the wrong one this can happen. This can happen anytime you connect an outlet from an uninstantiated storyboard.

Swift custom UITableviewCell width issue

I have created a custom UITableviewCell in xcode 6 beta(5), but while testing on the simulator it looks too small, I tried to set the width using attribute inspector, and it didn't worked. I created it using a .xib file and I registered it in my mainViewController to use it with connected tableView
This is how it looks like in simulator
The cell part of the code, where my custom class name is CustomCell
var cell:CustomCell = self.tableview.dequeueReusableCellWithIdentifier("cell") as CustomCell
cell.txt.text="\(ListArray.objectAtIndex(indexPath.row))"
return cell
This is how I register in viewDidLoad
var nipName=UINib(nibName: "CustomCell", bundle:nil)
self.tableview.registerClass(CustomCell.classForCoder(), forCellReuseIdentifier: "cell")
self.tableview.registerNib(nipName, forCellReuseIdentifier: "cell")
Take a look at my response to UILabels in custom UITableViewCell never gets initialized . First of all, code in the heightForRowAtIndexPath function. Second, depending on how you set up the nib/storyboard, if it already connected the tableview to the custom view, get rid of registerClass. Otherwise it'll disconnect your nib connection and recreate a new one, wiping out all the customization you did in the nib.

Failed to connect (storyboard) outlet from (NSApplication) to (NSNibExternalObjectPlaceholder) error in Cocoa and storyboard

I've tried to build a sample Cocoa app on which I want to connect UI components put on storyboard to ViewController.swift as either an IBOutlet or IBAction. However, when I tried to control-drag the UI components on storyboard (such as NSButton) to ViewController.swift and create a #IBAction method, and then run the app, the resultant app logs the following message in console and of course the app doesn't respond to me tapping the button.
Failed to connect (storyboard) outlet from (NSApplication) to (NSNibExternalObjectPlaceholder): missing setter or instance variable
How can I use the IBAction method properly?
For your information here's my ViewController.swift:
import Cocoa
class ViewController: NSViewController {
#IBOutlet var txtTitle : NSTextField
#IBOutlet var boxColor : NSBox
override func viewDidLoad() {
super.viewDidLoad()
}
func colorChanged(cp: NSColorPanel) {
let c:NSColor = cp.color;
self.boxColor.fillColor = c
}
#IBAction func btnSetColor(sender : AnyObject) {
let cp:NSColorPanel = NSColorPanel.sharedColorPanel()
cp.setTarget(self)
cp.setAction("colorChanged:")
cp.orderFront(nil)
}
#IBAction func btnSetWindowTitle(sender : AnyObject) {
if self.txtTitle.stringValue != "" {
println(self.title)
println(self.txtTitle.stringValue)
self.title = self.txtTitle.stringValue
}
}
}
I use Xcode 6 beta on OS X 10.10 Yosemite. And started the template with storyboard being on.
While the answer above correctly states that this isn't the reason for compilation issues, I thought that I would clarify for those who are just looking to eliminate the warning messages altogether. This was what I was looking for when I found this page.
When you are building your actions and some of the actions change, or get deleted in the storyboard, the outlets remain. Select the controller/window where the older unused actions used to be and you will still see them in the outlets segment of the storyboard within the attributes tab. Remove those old actions/outlets there and then the warning disappear.
Look for duplicates between the ViewController and the File's Owner. One or both might be holding on to these objects when they shouldn't be. Removing those will remove these soft warnings.
Failed to connect (storyboard) outlet from (NSApplication) to (NSNibExternalObjectPlaceholder): missing setter or instance variable
The IBAction methods working like it should, see Apple Dev Forums:
"This is a known issue ... The messages are harmless and do not
indicate a problem with your code."
Apple Dev Forums: OS X Storyboard failure
Thats not why your code is not working, you need to fix the following:
A) Here is my working code to set the title - using self.view.window.title instead self.title:
#IBAction func btnSetWindowTitle(sender : AnyObject) {
if self.txtTitle.stringValue != "" {
println(self.view.window.title)
println(self.txtTitle.stringValue)
self.view.window.title = self.txtTitle.stringValue
}
}
B) In Interface Builder you need to set NSBox "Box Type" to "Custom":
And that's it:
I think I figured out the right solution.
1) Drag an Object into you xib interface.
2) Click the Object in the left list you just dragged in.
3) Bind the Object to your custom class.(Here my class is a login window controller as example)
4) Ctrl drag button to the source code. In the popup window, choose your class name(here in example is Login Window Controller) rather than File's Owner.
Hope this could help you.
I've found another easier solution these days while coding.
Check this out.
1) Select File's Owner in Document Outline in the .xib file.
2) Specify the class you want the .xib file to connect with.
3) Now when you connect outlet to the source file, just use default File's Owner. Much easier.
4) I guess it's not enough so far. I've met an exception when running called 'loaded the 'xxx' nib but the view outlet was not set'. We should do something more.
Select the view in Document Outline. Drag from the circle of New Referencing Outlet to the File's Owner in Document Outline.
Alright, that's the new easier solution. No additional objects should add into the xib. If it doesn't work, leave comments below.

windowDidLoad() never called using storyboards for mac

I've just played around with the new mac storyboard-feature included in Xcode 6. I've set up a new OS X-project using storyboards and swift, then I've created a new file MainWindowController.swift, created the initializer init(coder: NSCoder!) (because otherwise the compiler warns me) and hooked everything up in the Main.storyboard file (set the MainWindowController-class for the WindowController in the inspector).
Everything compiles fine, my Window with the specified window content-view opens. But the code I've written in the windowDidLoad-function is never be called. Let it just something like:
override func windowDidLoad() {
super.windowDidLoad()
println("Executed")
}
I've also tested if my initializer is called - it is.
Does anybody has a clue? I've never used storyboards intensively on iOS before, maybe I miss something substantial.
In Yosemite, NSViewController has been promoted with powerful new features to make it work with Storyboards. Meanwhile, NSWindowController got demoted. With Storyboards, windows are no longer loaded from a nib, so windowDidLoad() doesn't get called anymore.
It makes sense for the window itself to become less important, in favor of a more powerful view it actually contains. My other answer on this page shows how to set up an AppDelegate to customize the window appearance. There's more detail on another page here, about using an AppDelegate to implement some of the things you might previously have done in an NSWindowController.
However, if you only wanted to catch windowDidLoad() as a way to customize the appearance options of the window, it is very easy to do that in Interface Builder, by simply adding them as User Defined Runtime Attributes to the NSWindow object. You don't need to subclass NSWindowController or write any code at all. Just plug in these values to the NSWindow object via the Identity Inspector pane to achieve the same effect shown in the AppDelegate example code:
Keypath: titlebarAppearsTransparent, Type: Boolean, Value: Checked
Keypath: titleVisibility, Type: Number, Value: 1
Keypath: styleMask, Type: Number, Value: 32783
Look in the headers to determine the actual numeric values of the constants.
( for example: NSWindowTitleVisibility.Hidden = 1 )
Of course, you can't specify individual bits of the styleMask, but it's easy enough to add them all together and get a single number to specify the style.
Remove everything except the Application scene from the Main.storyboard file, and instead, create a new Application.storyboard for the application window. Implement an application delegate class and connect it to the Application object in Main.storyboard. Use this class to instantiate the window controller and set up custom options for the application window.
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidBecomeActive(notification: NSNotification) {
let storyboard = NSStoryboard(name: "Application", bundle: nil)
applicationController = storyboard.instantiateInitialController() as? NSWindowController
if let window = applicationController?.window {
window.titlebarAppearsTransparent = true
window.titleVisibility = NSWindowTitleVisibility.Hidden
window.styleMask |= NSFullSizeContentViewWindowMask
applicationController!.showWindow(self)
}
}
}
Rather than subclassing NSWindowController, use the ViewController.swift subclass of NSViewController that Xcode creates for you automatically with the project.
In the storyboard, notice how there's a Relationship that connects the "window content" to the ViewController. So, the ViewController can now do things that you might previously have done in a window controller.
The ViewController.swift file will already have a default override of viewDidLoad() that will be called when the window loads, just as you were expecting windowDidLoad() to be called if it were an NSWindowController subclass.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
println("Executed")
}

Resources