iphone – 从xib加载UIView,在尝试访问IBOutlet时崩溃
发布时间:2020-12-15 01:49:52 所属栏目:百科 来源:网络整理
导读:我有一个xib文件,上面有一个小的UIView,后面又包含一些标签.现在,我正在尝试将UIView加载到现有的UIViewController中,并更改其中一个标签文本.我想这样做的原因是,UIView将被重复使用不同的标签文本,所以我想制作一个自定义类并从xib加载它将是最好的方法.
我有一个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链接到标题出口. CoverPanel *panelView = [[CoverPanel alloc] initWithFrame:CGRectMake(0,300,100)]; 到现在为止还挺好.它完全按照它在.xib中的布局显示UIView. panelView.headline.text = @"Test"; 它崩溃了这个错误: 这可能是我忽略的一些小事,但到目前为止,它已经让我疯了几个小时.有人有什么主意吗? 解决方法
您将自定义视图的类重新分配给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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |