Using xib programatically setting IBOutlet and file owner results in key value coding-compliant error

半城伤御伤魂 提交于 2019-12-12 03:59:35

问题


I create a xib. The file owner of the xib is a set to a custom class called PackageTrackingListViewElement. The PackageTrackingListViewElement has an IBOutlet property called contentView, among others. Several views in interface builder are connected to the IBOutlet properties of the custom class called PackageTrackingListViewElement.

I try to initialize an object from the xib.

PackageTrackingListViewElement *element2 = [[[NSBundle mainBundle] loadNibNamed:@"PackageTrackingListViewElementXib" owner:nil options:nil] objectAtIndex:0];

[element2.labelDate setText:@"12/14/15"];
[element2.labelLocation setText:@"Berkeley, California"];

After this, I add the element2 object to a UIStackView.

What am I supposed to set the file owner in loadNibNamed so that I do not get the error that the owner of the xib is not key-value compliant for the properties I am attempting to access?

My error is [<UIStackView 0x165ddc80> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key contentView.' When I try to set the stackView as the owner of the xib. I know this is wrong of course, but I cannot set the object which has not been created to be its own owner. I do not understand what to do.


回答1:


Alas figured it out. Many thanks to Instantiating a UIView from a XIB file with itself as the file's owner?

Thank you nebs

PackageTrackingListViewElement.h

#import <UIKit/UIKit.h>

@interface PackageTrackingListViewElement : UIView

@property (nonatomic,strong) IBOutlet UILabel *labelLocation;

- (instancetype)initFromNib;

@end

PackageTrackingListViewElement.m

#import "PackageTrackingListViewElement.h"

@implementation PackageTrackingListViewElement : UIView

- (instancetype)initFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:nil options:nil] firstObject];
}

@end

You can then simply do:

PackageTrackingListViewElement *myView = [[PackageTrackingListViewElement alloc] initFromNib];


[myView.labelLocation setText:@"text"]; //access properties

By using the instantiation procedure in the link above, I got my instantiation of the xib to work. I set the file-owner of the xib to nothing (NSObject), and instead set the root view (by selecting the view in the xib) to the PackageTrackingListViewElement and connecting all outlets to that view.



来源:https://stackoverflow.com/questions/33705659/using-xib-programatically-setting-iboutlet-and-file-owner-results-in-key-value-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!