Adding IBOulets to custom UIView subclass crashes 'is not key-value compliant' - ios

I have created two different subviews EPStudentProgressOpenQuestion and EPStudentProgressMultipleChoiceQuestion. They both inherit from EPStudentProgressQuestion as they both subviews share some common information and behaviours.
Each one of the views has its own XIB file.
Inside EPStudentProgressQuestion there is the following code:
#import "EPStudentProgressQuestion.h"
#interface EPStudentProgressQuestion ()
#property (assign, nonatomic) EPStudentProgressQuestionType questiontype;
#end
#implementation EPStudentProgressQuestion
#pragma mark - UIView lifecycle
- (instancetype)initWityQuestionType:(EPStudentProgressQuestionType)questionType {
self = [super init];
if (self) {
self.questiontype = questionType;
[self setupView];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setupView];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setupView];
}
return self;
}
#pragma mark - Private methods
- (void)setupView {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
UIView *view = [[bundle loadNibNamed:[self nibNameForQuestionType] owner:[self class] options:nil] firstObject];
view.frame = self.bounds;
[self.layer setCornerRadius:2.f];
[self.layer setBorderWidth:1.f];
[self.layer setBorderColor:[UIColor colorWithWhite:232/255.f alpha:1.f].CGColor];
[self setClipsToBounds:YES];
[self setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:view];
}
- (NSString*)nibNameForQuestionType {
switch (self.questiontype) {
case EPStudentProgressQuestionTypeOpen:
return #"EPStudentProgressOpenQuestion";
case EPStudentProgressQuestionTypeMultipleChoice:
return #"EPStudentProgressMultipleChoiceQuestion";
}
}
As you can see, very simple code.
As I said above, each EPStudentProgressQuestion view has its own XIB file, connecting the Files Owner through the Identity Inspector class.
This is EPStudentProgressOpenQuestion:
#import "EPStudentProgressOpenQuestion.h"
#interface EPStudentProgressOpenQuestion ()
#property (weak, nonatomic) IBOutlet UILabel *lblQuestion;
#end
#implementation EPStudentProgressOpenQuestion
#end
Exactly the same for EPStudentProgressMultipleChoiceQuestion just without any IBOutlet. But as soon as I create IBOutlets to any of those views, I get the error ... IBOutlet is not key-value compliant...
Without the IBOutlets everything works fine. Each view loads correctly and it's well placed in the view I want to. But as soon as I link some IBOutlets from the XIB to the corresponding class, it crashes...
This is the crash:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<EPStudentProgressQuestion 0x1020196b0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key lblQuestion.'
And this is how I instantiate the EPStudentProgressQuestion view:
EPStudentProgressOpenQuestion *questionView = [[EPStudentProgressOpenQuestion alloc] initWityQuestionType: EPStudentProgressQuestionTypeOpen];
[self.vQuestionsContainer addSubview:questionView];
Any idea on how to be able to link IBOutlets without having problems?
Thank you in advance!!
EDIT:
If I change the bundle and owner classes as follows:
NSBundle *bundle = [NSBundle bundleForClass:[EPStudentProgressOpenQuestion class]];
NSArray *views = [bundle loadNibNamed:[self nibNameForQuestionType] owner:[EPStudentProgressOpenQuestion class] options:nil];
UIView *view = [views firstObject];
I get the same error but instead of EPStudentProgressQuestion I get the error for EPStudentProgressOpenQuestion...
EDIT 2:
Test project link: https://mega.nz/#!oBhWkawC!RSOzrPOfq_UTVWd3jraRkneuCIyIkS61PKGeca2Bilc

The problem that's crashing you is that you are passing [self class] instead of just self as the nib owner. Change your nib loading line to this:
NSArray *views = [bundle loadNibNamed:[self nibNameForQuestionType] owner:self options:nil];
You have another problem which is that you're loading the nib twice. In initWityQuestionType:, you call [super init]. What you don't realize is -[UIView init] calls [self initWithFrame:CGRectZero]. So you end up calling into your overridden initWithFrame:, which calls setupView. Then when it returns back to initWityQuestionType:, that also calls setupView.
I recommend you get rid of your initWithFrame: override entirely.

Your crash indicates that EPStudentProgressQuestion (your superclass) is not key-value compliant. This means at the point where you are accessing the IBOutlet you have a reference to EPStudentProgressQuestion instead of either EPStudentProgressOpenQuestion or EPStudentProgressMultipleChoiceQuestion.
Just check the code where you are using the new IBOutlets and either change the type of the variable used there or add a cast to the correct class.

Your view controller may have the wrong class in your xib. Please change the UIView class name not the in the File's Owner like the pic
Also you called a [self setup] method in:
- (instancetype)initWityQuestionType:(EPStudentProgressQuestionType)questionType {
self = [super init];
if (self) {
self.questiontype = questionType;
[self setupView];
}
return self;
}
You don't need to call it again
- (instancetype)initWithFrame:(CGRect)frame {
}
and
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
}
it is creating a init loop and causing a memory leak.

Related

IB_DESIGNABLE not showing up in Interface Builder

I'm making a custom UI component in XCode 6.4, using Objective-C. In the main storyboard where I use the component whenever I change one of the IBInspectable values I get the following error:
Main.storyboard: warning: IB Designables: Ignoring user defined runtime attribute for key path "icon" on instance of "UIView". Hit an exception when attempting to set its value: [<UIView 0x7fc33a5601c0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key icon.
I'm loading a .xib file and I'm overriding the initWithCoder & initWithFrame methods as follows:
- (void) loadView {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
UIView *view = [[bundle loadNibNamed:#"TheNameOfTheNIB" owner:self options:nil] firstObject];
[self addSubview:view];
view.frame = self.bounds;
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[iconButtton setImage:_icon forState:UIControlStateNormal|UIControlStateSelected];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self && self.subviews.count == 0) {
[self loadView];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self loadView];
}
return self;
}
In initWithCoder: I had to use a check if there was a subview because it was going into an infinite loop (the xib file in loadView is calling initWithCoder: again.
So when I build and run this it shows up correctly (but only with the default values in the NIB not with the correct ones I pass in the storyboard), but the live preview of the component doesn't show up in Interface Builder at all.
Update
Here's the header file for the custom UI component
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface CustomComponent : UIView
#property (assign, nonatomic) IBInspectable UIImage *icon;
#property (weak, nonatomic) IBOutlet UIButton *iconButtton;
#end

Custom UIView loaded from Xib

I have created a custom subclass of UIView along with a xib file and declared IBOutlets and IBActions within the custom class.
#interface ContactUsView : UIView
#property (nonatomic, weak) IBOutlet UIButton *displayCloseButton;
- (IBAction)callButtonPressed:(id)sender;
- (IBAction)emailButtonPressed:(id)sender;
- (IBAction)displayCloseButtonPressed:(id)sender;
#end
In the xib file I have dragged in a UIView to represent my custom view. I have set:
Files owner = to my custom class
Have set the dragged in UIView to my custom class.
I have then added various buttons which are hooked up to the 3 methods stated above.
Inside the ContactUsView.m I have the following:
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
NSArray* array = [[NSBundle mainBundle] loadNibNamed:#"ContactUsView" owner:self options:nil];
for (id object in array) {
if ([object isKindOfClass:[ContactUsView class]])
self = (ContactUsView *)object;
}
}
return self;
}
When I come to create this view I do the following:
- (void)viewWillAppear:(BOOL)animated
{
ContactUsView *contactUs = [[ContactUsView alloc] initWithFrame:CGRectZero];
CGPoint origin = self.view.frame.origin;
CGSize size = self.view.frame.size;
[contactUs setFrame:CGRectMake(origin.x,
CGRectGetMaxY(self.view.frame) - 100,
size.width,
contactUs.frame.size.height)];
[self.view addSubview:contactUs];
}
Issue
When I press on one of the buttons the application crashes with:
Thread 1: EXC_BAD_ACCESS(code=2, address=0xb0c
Can anyone help me with this. I feel like I am probably making a mistake somewhere in regards to creating and loading custom uiviews from xibs.
If you require anymore information let me know. Many thanks.
Future reference
When creating a custom view using a xib DO NOT set the files owner. Instead create all your IBOutlets and IBActions as you normally would and then to hook them up open the Utilities tab and control drag from there.
• Files owner = to my custom class
Wrong. Files owner should be empty. The view itself is files owner. It means that you should connect all actions and outlets with ContactUsView in your xib.
[[NSBundle mainBundle] loadNibNamed:#"ContactUsView" owner:self options:nil]
...
self = (ContactUsView *)object;
After you passed self as ownerparameter. You changing it. Which means that previously allocated ContactUsView (self) will be destroyed since -loadNibNamed:owner:options: do not retain it. If you apply my first advice you should send nil as owner parameter
forloop here is not necessary use just array[0], because this is always your view if you have valid views hierarchy in your xib
If you are loading a UIView for an xib then you should create a class method to load the view.
In your customview.h
+(id)customView;
& in your customview.m
+ (id)customView
{
CustomView *customView = [[[NSBundle mainBundle] loadNibNamed:#"CustomView" owner:nil options:nil] lastObject];
if ([customView isKindOfClass:[CustomView class]])
return customView;
else
return nil;
}
You can initialize it anywhere using:
CustomView *myView = [CustomView customView];
EDIT: Make sure you have changed your customview's class in identity inspecter & also make sure your connection of IBActions are with that class' methods.
You can use delegate for this
this is how you can do this
#protocol CustomViewDelegate <NSObject>
- (void)callButtonPressed:(id)sender;
- (void)emailButtonPressed:(id)sender;
- (void)displayCloseButtonPressed:(id)sender;
#end
#interface ContactUsView : UIView
#property (nonatomic, weak) IBOutlet UIButton *displayCloseButton;
#property (nonatomic, weak) id<CustomViewDelegate> ButtonDelegate;
- (IBAction)callButtonPressed:(id)sender;
- (IBAction)emailButtonPressed:(id)sender;
- (IBAction)displayCloseButtonPressed:(id)sender;
#end
and in .m file
- (IBAction)callButtonPressed:(id)sender
{
[self.ButtonDelegate callButtonPressed:sender];
}
- (IBAction)emailButtonPressed:(id)sender{
[self.ButtonDelegate emailButtonPressed:sender];
}
- (IBAction)displayCloseButtonPressed:(id)sender{
[self.ButtonDelegate displayCloseButtonPressed:sender];
}
After that just set the delegate with viewcontroller refrence and use those delegate here
- (void)viewWillAppear:(BOOL)animated
{
ContactUsView *contactUs = [[ContactUsView alloc] initWithFrame:CGRectZero];
contactUs.ButtonDelegate = self;
CGPoint origin = self.view.frame.origin;
CGSize size = self.view.frame.size;
[contactUs setFrame:CGRectMake(origin.x,
CGRectGetMaxY(self.view.frame) - 100,
size.width,
contactUs.frame.size.height)];
[self.view addSubview:contactUs];
}
- (void)callButtonPressed:(id)sender
{}
- (void)emailButtonPressed:(id)sender
{}
- (void)displayCloseButtonPressed:(id)sender
{}
I have done this and works totlly fine

How to initialize a UIView subclass loaded from a xib?

There are countless answers on how to subclass UIView, but none of them seem to help me.
I have a UIView Subclass
#import <UIKit/UIKit.h>
#interface DarkSeparatorUIView : UIView
#end
And the implementation:
#import "DarkSeparatorUIView.h"
#implementation DarkSeparatorUIView
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Do something
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
// Do something
}
return self;
}
#end
In a separate xib I am creating a UIView and marking its class as "DarkSeparatorUIView". I expect that when the view loads that initWithCoder would be called, but it's not. Am I missing something?
Edit: I've tried awakeFromNib and it doesn't work, as well.
Edit2: This works in a fresh project, but not in my current project. I don't know what is different?
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self = [[[NSBundle mainBundle] loadNibNamed:#"DarkSeparatorUIView" owner:self options:nil] objectAtIndex:0];
}
return self;
}
make sure your xib named DarkSeparatorUIView.xib
My issue was that when I created DarkSeparatorUIView, I didn't include it in all of my build targets. If you didn't do this when you created the file, you can click on the file in Project Navigator, then select the File Navigator and select the targets you want the file to be available for.
Apple has created a category on NSBundle declared in UINibloading.h. It adds the method loadNibNamed:owner:options to NSBundle, which makes it pretty easy to load a nib from a bundle.
I have created a category on UIView for this purpose. It defines a single method:
+(instancetype)viewFromNib
Include this category in the header of your custom UIView subclass to enable loading it from a nib using this one liner:
MyView *view = [MyView viewFromNib];
I've put the category in a gist, but the code loading the nib goes like this:
NSString *className = NSStringFromClass([self class]);
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:className owner:self options:nil];
id view = nil;
for (id object in bundle) {
if ([object isKindOfClass:[self class]]) {
view = object;
}
}

Custom UIView from nib inside another UIViewController's nib - IBOutlets are nil

I'm trying to create a custom UIView which holds references to its own IBOutlets. I then want to put this custom UIView into another nib.
I'm doing some additional logic in the custom UIView's awakeFromNib method. Unfortunately, when I try to access the IBOutlets in awakeFromNib, they are nil.
Here's the setup:
I have a UIView subclass, CustomView.
I have a custom .xib file with three subviews
In the other nib (that belongs to the view controller), I have dragged a UIView onto the view, and then changed the custom class to CustomView.
I tried setting the view in the CustomView nib in IB to a custom class CustomView and connecting the IBOutlets to the view, but they were still nil.
I tried setting file owner to CustomView and connecting the IBOutlets to file's owner, but they were still nil.
I also tried using another IBOutlet UIView *view and then adding that as a subview to self in awakeFromNib but that also didn't do anything.
Here's the code:
// CustomView.h
#interface CustomView : UIView
#property (nonatomic, retain) IBOutlet UITextField *textField;
#property (nonatomic, retain) IBOutlet UIView *subview1;
#property (nonatomic, retain) IBOutlet UIView *subview2;
// CustomView.m
#implementation CustomView
#synthesize textField, subview1, subview2;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[[NSBundle mainBundle] loadNibNamed:#"CustomView" owner:self options:nil];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (void)setup {
// Fails because self.textField is nil
self.textField.text = #"foo";
}
I ended up using the steps in the most recent edit here and they worked beautifully.
You use a plain UIView as the top level view in the xib.
You then set file's owner to the custom subclass (CustomView).
Finally, you add a line:
[self addSubview:[[[UINib nibWithNibName:#"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0]];
in the if (self != nil) block in both initWithCoder and initWithFrame.
Voila! The IBOutlets are hooked up and ready to go after the call. Really pleased with the solution, but it was very difficult to dig up.
Hope this helps anyone else.
EDIT: I updated the link to one that isn't dead. Since I never spelled out the full code, here is what it looks like after modification:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIView *nib = [[[UINib nibWithNibName:#"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
[self addSubview:nib];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
UIView *nib = [[[UINib nibWithNibName:#"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
[self addSubview:nib];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (void)setup {
// Doesn't fail because life is awesome
self.textField.text = #"foo";
}
This pattern has become so common that I actually created a category on UIView called UIView+Nib, which implements the following method:
+ (UIView *)viewWithNibName:(NSString *)nibName owner:(id)owner {
return [[[UINib nibWithNibName:nibName bundle:nil]
instantiateWithOwner:owner options:nil]
objectAtIndex:0];
}
So the above code can be simplified to:
[self addSubview:[UIView viewWithNibName:#"CustomView" owner:self]];
Note also that the above code can be refactored even more, since the logic is exactly the same in initWithFrame: and initWithCoder:. Hope that helps!
As in Dr. Acula's answer, This is probably because custom view's nib is lazy loaded when loaded from another nib (Nested nib loading), so we need to instantiate it manually. In swift code will look like this :
override func awakeFromNib() {
super.awakeFromNib()
self.customview = UINib(nibName: "CustomViewNib", bundle: nil).instantiateWithOwner(self, options:nil)[0] as! UIView
self.customview?.frame = self.viewContainer.bounds
self.viewContainer.addSubview(self.customview!)
}
I am assuming the XIBs' structure is something like this
CustomView.xib
CustomView
UITextField -> linked to IBOutlet textField
other views
CustomViewController.xib
CustomView
If this is right, then your CustomView will be created but as it is not read from CustomView.xib it doesn't have any IBOutlets assigned.
However, if your CustomViewController.xib looks like following
CustomViewController.xib
CustomView
UITextField -> linked to IBOutlet textField of CustomView
then this should work. The IBOutlet of CustomView instance should be set by the CustomViewController.xib.
Better than setting any IBOutlets in the CustomViewController.xib would be to implement awakeAfterUsingCoder: in your CustomView and create a replacement object by loading your CustomView.xib in there. This way your CustomView remains truly custom and you don't have to edit other XIBs to change the structure, add/remove IBOutlets, etc.

iOS UIView subclass with NIB file does not display the UI designed in IB

I have a class that inherits from UIView, and this class has some controls that I have placed on it in IB.
Then, in the NIB file for my main view controller, I placed a view, and changed the class to my subclass, and created an outlet for the subclass. However, when I run my application, the app does not display the UI that I put on the subclass, it is just blank.
I am getting the initWithCoder and awakeFromNib messages in the subclass, here is what the subclass .m file basically looks like:
#import "AnalyticsDetailView.h"
#implementation AnalyticsDetailView
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
NSArray *v = [[NSBundle mainBundle] loadNibNamed:#"AnalyticsDetailView" owner:self options:nil];
[self addSubview:[v objectAtIndex:0]];
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
#end
I am not sure if the initWithFrame is correct, but since that method is not firing, I suspect that it doesn't matter at this point. If I put a breakpoint in my app after I have seen the subclass methods fire, I can look at the outlet subclass and the frame is the same as what I have created in IB.
Anyone have any suggestions (missing code, bad IB connections, etc.) on what to look for that I have missed or am doing incorrectly? Thanks.
To get your interface to appear, you'll need to explicitly instantiate a AnalyticsDetailView from your parent view controller.
So in somewhere like the viewDidLoad: or viewWillAppear: methods, you'll add a line that says:
AnalyticsDetailView * newView = [[AnalyticsDetailView alloc] initWithFrame: CGRectMake(x,y,height,width)];
[parentView addSubview: newView];
[newView release]; // subview retains for us

Resources