【问题标题】:Loading UIView from xib, crashes when trying to access IBOutlet从 xib 加载 UIView,尝试访问 IBOutlet 时崩溃
【发布时间】:2011-08-27 16:59:34
【问题描述】:

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

我尝试了几种加载方式,并成功地在我的视图控制器上显示了它。问题是,一旦我尝试在 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 链接到标题出口。 在我的视图控制器中,这是我创建 CoverPanel 实例的方法,这就是它崩溃的地方:

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

到目前为止,一切都很好。它完全按照 .xib 中的布局显示 UIView。 但是一旦我尝试像这样更改headline.text

panelView.headline.text = @"Test";

它会因以下错误而崩溃: 由于未捕获的异常“NSInvalidArgumentException”而终止应用,原因:“-[UIView 标题]:无法识别的选择器已发送到实例 0x5c22b00”

这可能是我忽略的一些小东西,但到目前为止,它已经让我发疯了好几个小时。有人知道吗?

【问题讨论】:

    标签: iphone xcode uiview nib


    【解决方案1】:

    您将自定义视图的类重新分配给 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;
    }
    

    【讨论】:

    • 哦,当然,这很有道理。现在可以使用了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2018-07-31
    相关资源
    最近更新 更多