gpt4 book ai didi

ios - Objective-C 中的自定义构造函数

转载 作者:行者123 更新时间:2023-11-28 18:01:13 24 4
gpt4 key购买 nike

我创建了一个扩展 UIView 的自定义类。这个类有一些方法比如Drawerect...

到目前为止,我只是把它放在我的 Storyboard中并告诉它属于这个类(class)。我现在将动态分配和放置这些对象。有没有一种方法可以调用:

[[MyObj alloc] initWithFrame:....] 

我很高兴能找到任何帮助!

最佳答案

您可以在类的头文件中创建自己的构造函数。返回值是 id 类型,在主文件的声明中需要调用 super 初始化(例如 self = [super initWithFrame:CGRect])然后返回 self。您可以在头文件中自定义构造函数的参数以满足您的需要。

UIView 示例:

.h:

#import <UIKit/UIKit.h>
@interface CustomView : UIView
-(id)initWithFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor;

.m:

#import "CustomView.h"

@implementation CustomView
-(id)initWithFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor{

self = [super initWithFrame:frame];

if (self) {

//after allocation you could set variables:

self.backgroundColor = backgroundColor;

}

return self;
}

@end

关于ios - Objective-C 中的自定义构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24937290/

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