Ios UIView:如何在调用initWithFrame之前设置属性?

Ios UIView:如何在调用initWithFrame之前设置属性?,ios,objective-c,uiview,initialization,Ios,Objective C,Uiview,Initialization,我有一些MyView作为UIView的子类,方法如下: @interface MyView : UIView @property (nonatomic, strong) UIImage *image; @end @implementation - (id)initWithImage:(UIImage *)image { self = [self init]; self.image = image; return self; } - (id)initWithF

我有一些
MyView
作为
UIView
的子类,方法如下:

@interface MyView : UIView

@property (nonatomic, strong) UIImage *image;

@end

@implementation

- (id)initWithImage:(UIImage *)image {
    self = [self init];
    self.image = image;

    return self;
}


- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //here I want to access my image property
    }
}

@end
在这个类中,我初始化对象如下:

[[MyView alloc] initWithImage: someimage];
initWithFrame:
是必需的,
initWithImage:
是可选的

如果您使用initWithImage初始化“MyView”,我怀疑它是否会调用initWithFrame。我建议你使用

   - (id)initWithFrame:(CGRect)frame :(UIImage *)image
或者更好

   - (id)initWithFrame:(CGRect)frame image:(UIImage *)image. 
所以您可以在相同的方法调用中传递图像。一定要加上

   - (id)initWithFrame:(CGRect)frame image:(UIImage *)image; 

也在.h文件中。

在调用初始化器之前,不能设置对象的属性,因为在调用初始化器之前,对象不存在。如果初始化器需要访问属性,则需要将其作为参数提供(因为这是成功创建对象的必要条件)

采用
CGRect
参数,因为此方法的目的是创建具有预定义帧的实例;它将功能添加到默认的
NSObject
-(instancetype)init
,因此随
frame
参数一起提供

ui视图
需要一个框架,以便可以在屏幕上进行布局和渲染(以及其他内容)。在实现过程中的某个时刻,它将执行对默认的
[super init]
方法的调用,然后访问
self
,以处理它所交的帧。它构建在现有类的基础上

您正在构建
UIView
类,希望能够使用
UIImage
对其进行初始化。您可以选择为子类提供默认框架:

- (instancetype)initWithImage:(UIImage *)image {

    if (self = [super initWithFrame:CGRectMake(0,0,0,0)]) {
        self.image = image;
    }
}
或者提供一个更“有用”的默认值(与我们一样),并将图像尺寸作为默认帧:

初始化UIImageView对象

-(instancetype)initWithImage:(UIImage*)image

讨论 此方法调整接收器的帧以匹配指定图像的大小。默认情况下,它还禁用图像视图的用户交互

使用初始化器,如:

- (instancetype)initWithImage:(UIImage *)image {

    if (self = [super initWithFrame:CGRectMake(0,0,image.size.width,image.size.height)]) {
        self.image = image;
    }
}
- (instancetype)initWithImage:(UIImage *)image {

    if (self = [super initWithFrame:CGRectMake(0,0,image.size.width,image.size.height)]) {
        self.image = image;
    }
}