我有一个xib文件,上面有一个小的UIView,后面又包含一些标签.现在,我正在尝试将UIView加载到现有的UIViewController中,并更改其中一个标签文本.我想这样做的原因是,UIView将被重复使用不同的标签文本,所以我想制作一个自定义类并从xib加载它将是最好的方法.
我已经尝试了几种加载它的方法,并且我已经在我的viewcontroller上成功显示了它.问题是,一旦我尝试在Interface Builder中实际链接IBOutlet并访问它,我的应用程序崩溃了.
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; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。