init UIView with parameters

2019-08-30 16:49发布

问题:

I have UIView class that presents view that is created programaticly in a controller.

When creating (initing) the UIView I would like to transfer parameters from the UIViewController, so instance variables of the UIView can be initialized. I want it to happen before awakeFromNib is called. So in awakeFromNib I could use these parameters.

I guess I need to do it in - (id)initWithCoder:(NSCoder *)aDecoder, but how? It only receives the aDecoder

Something like this:

- (id)initWithCoder:(NSCoder *)aDecoder {

    if(self = [super initWithCoder:aDecoder]) {
         _instanceParameter = parameterFromController;
    }

    return self;
}


-(void)awakeFromNib{
    if (_instanceParameter)
         do logic
}

回答1:

I'm guessing you've subclassed "UIView" into something, let's call it "LudaView".

Expose a property for your parameters and when you load it from your xib file, you can set your parameters there. In other words:

_myUIView = (LudaView *) [[[NSBundle mainBundle] loadNibNamed:@"myUIView" owner:self options:nil] objectAtIndex:0];
if(_myUIView)
{
    _myUIView.parameters = parametersFromViewController;
}

You could also set a BOOL property or ivar within your "LudaView" and then when a drawing method is called for the first time, you can set stuff up. E.G.

- (void)drawRect:(CGRect)rect
{
   if(everythingSetUp == NO)
   {
      // do stuff with your parameters here
      everythingSetUp = YES;
   }
   // you shouldn't need to call [super drawRect: rect] here if 
   // subclassing directly from UIView, according to Apple docs
}


回答2:

From your question, at lot of things are a bit unclear. When you create your custom view, you can call a second init function. Something like this:

// In the UIViewController
NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"CustomView"
                                              owner:self
                                            options:nil];
CustomView *myView = [[nibs objectAtIndex:0] initWithParameter:myParameter];
[self.view addSubview:myView];

Then in your UIView class:

- (id) initWithParameter:(id)parameter
{
    _instanceParameter = parameter;
    // Do whatever initialization you need to
    ...
    return self;
}

Just do all of the initialization you need to in the initWithParameter method.