gpt4 book ai didi

ios - 使用参数创建自定义 UIView init 方法

转载 作者:可可西里 更新时间:2023-11-01 03:54:24 24 4
gpt4 key购买 nike

我正在寻找如何使用传入参数的自定义 init 方法正确子类化 UIView

我已阅读此处的 UIView 类引用文档:https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html

目前 UIView 是在 UIViewController 中创建的,可以移动/重构到它自己的子类中。此外,目前 View 完全在代码中创建,框架由添加到 View 本身的约束计算。

文档说明如下

initWithFrame: - It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method.

问题
因为我没有创建一个框架作为 View 的起点/它也不是从 XIB 加载的,所以子类化它的正确过程是什么?

这是否正确:

-(id)init {
NSLog(@"%s",__PRETTY_FUNCTION__);
self = [super init];
if (self) {
// Init code
[self spmCustomInit];
}
return self;
}

-(void)spmCustomInit {
NSLog(@"%s",__PRETTY_FUNCTION__);

}

如果这是正确的,我需要进一步更改它。创建 View 时,它会根据信息创建一些 subview 。布局也因难度级别而异。进一步的问题
如何创建一个我传入参数的进一步自定义初始化方法?
例如,如果我创建了一个名为

的方法
spmInitWithWord:(NSString *)word difficulty:(GameTurnDifficulty)difficulty

然后如何调用标准的 init 方法。然后我会在最初创建 View 时调用这个自定义 init 吗? [[UICustomViewExample alloc] spmInitWithWord:testWord difficulty:turnDifficulty]??

最佳答案

不,我建议采用不同的方法。编写您的 init 方法来调用 super initWithFrame。这是 UIView 的指定初始化器。通过自己调用它,您可以确保调用任何需要进行的操作系统设置。

如果需要,可以传入CGRectZero作为frame,稍后设置frame。

请注意,您还应该计划支持使用 initWithCoder 进行初始化。如果将 View 放入 XIB 文件或 Storyboard 中,就会调用该方法。

我所做的是创建一个方法 doInitSetup,并将我的自定义初始化放在那里。然后,我从 initWithFrame 和 initWithCoder 调用该方法。

在您的情况下,您可以为自定义设置添加属性,如果您将其中一个 View 放在 XIB/Storyboard 中,则可以使用用户运行时属性设置这些属性。

使用 IB 来设计表单是个好主意。我建议你学习使用它们。它们使喜欢变得更容易,并使您能够访问几乎不可能通过代码使用的功能。

您的代码可能如下所示:

- (id) initWithWord: (NSString *) theWord
{
self = [super initWithFrame: CGRectZero];
if (!self)
return nil;
[self doInitSetupWithWord: theWord];
return self;
}

- (void) doInitSetupWithWord: (NSString *) theWord
{
//Do whatever you need to do to set up your view.
}


- (id) initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder: aDecoder];
if (!self) {
return nil;
}

[self doInitSetupWithWord: nil];
return self;
}

- (void) setWord: (NSString *) theWord
{
_theWord = theWord;
//If possible, set things up for the new word
}

关于ios - 使用参数创建自定义 UIView init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21989138/

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