简体   繁体   English

具有自定义初始化的自定义UIView不起作用

[英]Custom UIView with custom initialization doesn't work

I'm developing an iOS app with latest SDK. 我正在使用最新的SDK开发iOS应用。

I have created a class that inherits from UIView and I have to do some initialization every time the class is instantiated. 我创建了一个从UIView继承的类,每次实例化该类时都必须进行一些初始化。

I have to call a method called setUpVars: but I don't know where to send a message to that method: 我必须调用一个名为setUpVars:的方法setUpVars:但是我不知道将消息发送到该方法的位置:

- (id)initWithFrame:(CGRect)frame;
- (id)initWithCoder:(NSCoder*)aDecoder;

This class can be used with a custom xib, or added to a Storyboard, so I need to be sure that that method will be called on every case. 此类可以与自定义xib一起使用,也可以添加到Storyboard中,因此我需要确保在每种情况下都将调用该方法。

- (void)setUpVars
{
    _preferenceKey = @"";
    _preferenceStatus = NO;
    _isDown = NO;
}

Where do I have to add [self setUpVars]; 我必须在哪里添加[self setUpVars]; ?

Essentially you will be wanting to cover both cases 本质上,您将要涵盖这两种情况

- (id)initWithFrame:(CGRect)frame;
{
  self = [super initWithFrame:frame];
  if (self) {
    [self setUpVars];
  }
  return self;
}

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

I think that you need to send this message from each method, also do not forget about awakeFromNib method. 我认为您需要从每个方法发送此消息,也不要忘记awakeFromNib方法。

You can create BOOL variable, something like isAlreadySetup and set it to YES in setUpVars method. 您可以创建BOOL变量(类似于isAlreadySetup ,然后在setUpVars方法中将其设置为YES

If you use Interface Builder to design your interface, initWithFrame : is not called when your view objects are subsequently loaded from the nib file. 如果使用Interface Builder设计界面,则随后从nib文件加载视图对象时,不会调用initWithFrame Instead initWithCoder gets called. 而是调用initWithCoder So you can initialize your variables in both methods if you prefer a generic way. 因此,如果您喜欢通用方法,则可以在两种方法中初始化变量。 Works in both case 在两种情况下均有效

Docs Says Docs说

awakeFromNib awakeFromNib

Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file. 从Interface Builder档案或nib文件中加载接收器后,为接收器做准备。

- (void)awakeFromNib
{
 [self setUpVars];
}

我倾向于认为您应该从负责控制器的-(void)viewDidLoad方法调用此方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM