iPhone - 从笔尖加载带有自定义 UI 的 UIView?
我有一个 UIView,我从 nib 文件初始化它。
在我的 nib 文件中,我拖放了一个 UIImageView 并将类名更改为 MyImage。
当我加载视图时,它似乎没有使用我的自定义类初始化图像,因为 init 方法没有被调用。 知道问题是什么吗?
@interface MyView : UIView
@property (nonatomic, retain) IBOutlet MyImage *image;
@end
@implementation MyView
@synthesize image;
- (id)init
{
self = [super initWithNibName:@"MyView" bundle:nibBundleOrNil];
return self;
}
@end
这是我的图片 这是我的图片
@interface MyImage : UIImageView
@end
@implementation MyImage
- (id)init
{
// This doesn't get called
self = [super init];
if (self)
{
// do somethin
}
return self;
}
@end
I have a UIView and I initialize it from a nib file.
In my nib file I dragged and dropped a UIImageView and I changed the class name to MyImage.
When i load the view it doesn't seem like it's initializing the the image using my custom class, because the init method is not getting called.
Any idea what the problem is?
@interface MyView : UIView
@property (nonatomic, retain) IBOutlet MyImage *image;
@end
@implementation MyView
@synthesize image;
- (id)init
{
self = [super initWithNibName:@"MyView" bundle:nibBundleOrNil];
return self;
}
@end
Here is MyImage
Here is my Image
@interface MyImage : UIImageView
@end
@implementation MyImage
- (id)init
{
// This doesn't get called
self = [super init];
if (self)
{
// do somethin
}
return self;
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从笔尖加载视图时使用的初始值设定项是
-initWithCoder:
,而不是-init
。从 UIView 参考页面:此外,如果您以编程方式实例化视图,则通常的初始化程序是
-initWithFrame:
。因此,将您的
-init
方法更改为-initWithCoder:
,或实现-initWithCoder:
以便它调用您的-init.
The initializer that's used when loading a view from a nib is
-initWithCoder:
, not-init
. From the UIView reference page:Moreover, if you're instantiating the view programmatically, the usual initializer is
-initWithFrame:
.So, change your
-init
method to-initWithCoder:
, or implement-initWithCoder:
such that it calls your-init
.Caleb 是对的,像这样实现它:
Caleb is right, implement it like so :
我认为 awakeFromNib 更安全,因为所有插座都正确连接
按顺序调用:
I though awakeFromNib was safer as all outlets wired up correctly
Called in order: