iphone – 从xib加载UIView,在尝试访问IBOutlet时崩溃

我有一个xib文件,上面有一个小的UIView,后面又包含一些标签.现在,我正在尝试将UIView加载到现有的UIViewController中,并更改其中一个标签文本.我想这样做的原因是,UIView将被重复使用不同的标签文本,所以我想制作一个自定义类并从xib加载它将是最好的方法.

我已经尝试了几种加载它的方法,并且我已经在我的viewcontroller上成功显示了它.问题是,一旦我尝试在Interface Builder中实际链接IBOutlet并访问它,我的应用程序崩溃了.

我创建了一个自定义的UIView类,如下所示:

CoverPanel.h

@interface CoverPanel : UIView {

    IBOutlet UILabel *headline;

}

@property (nonatomic,retain) IBOutlet UILabel *headline;

@end

CoverPanel.m

@implementation CoverPanel

@synthesize headline;

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code.
        //
        self = [[[NSBundle mainBundle] loadNibNamed:@"CoverPanel" owner:self options:nil] objectAtIndex:0];
    }
    return self;
}

在CoverPanel.xib中,我将UILabel链接标题出口.
在我的viewcontroller中,这是我创建CoverPanel实例的方式,这就是它崩溃的地方:

CoverPanel *panelView = [[CoverPanel alloc] initWithFrame:CGRectMake(0,300,100)];

到现在为止还挺好.它完全按照它在.xib中的布局显示UIView.
但是一旦我尝试更改headline.text就像这样:

panelView.headline.text = @"Test";

它崩溃了这个错误
因未捕获的异常’NSinvalidargumentexception’而终止应用程序,原因:’ – [UIView标题]:无法识别的选择器发送到实例0x5c22b00′

这可能是我忽略的一些小事,但到目前为止,它已经让我疯了几个小时.有人有什么主意吗?

解决方法

您将自定义视图的类重新分配给xib中的视图.你不需要这样做因为那时你得到的是来自xib的视图,你刚刚泄露了你的CoverPanel.所以,只需更换初始化程序:

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // No need to re-assign self here... owner:self is all you need to get
        // your outlet wired up...
        UIView* xibView = [[[NSBundle mainBundle] loadNibNamed:@"CoverPanel" owner:self options:nil] objectAtIndex:0];
        // Now add the view to ourselves...
        [xibView setFrame:[self bounds]];
        [self addSubview:xibView]; // we automatically retain this with -addSubview:
    }
    return self;
}

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...