gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:27:46 26 4
gpt4 key购买 nike

我有一些 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:是可选的

最佳答案

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

- (id)initWithFrame:(CGRect)frame

接受一个CGRect参数,因为这个方法的目的是创建一个带有预定义框架的实例;它为默认 NSObject- (instancetype) init 添加了功能,因此提供了 frame 参数以供使用。

UIView 需要一个框架,以便它可以在屏幕上布局并呈现(除其他外)。在实现的某个时刻,它将执行对默认 [super init] 方法的调用,然后访问 self 以处理它已处理的框架。它构建在现有类的基础上。

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

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

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

或者提供一个更有用的默认值(比如 UIImageView 会做)并将图像尺寸作为默认框架:

Initializing a UIImageView Object

- (instancetype)initWithImage:(UIImage *)image

DiscussionThis method adjusts the frame of the receiver to match the size of the specified image. It also disables user interactions for the image view by default.

使用像这样的初始化器:

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

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

关于ios - UIView:如何在调用 initWithFrame 之前设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28586014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com