lazy instantiation UIImageView

304 Views Asked by At

I am trying to look at most efficient way of initialising UIIMageViews within a custom UIView class which is placed within a Custom UITableCell

My custom view has more than one button. In essence I am trying replicate the standard way of setting UIImageviews from within a cell. The current way I am trying creates the UIImageview lazily but the image property of UIImageview is null. if I call the getter a second time it is not.

So in my tableview

 - (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  
  *)indexPath {
    static NSString *CellIdentifier = @"Cell";
   _cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (_cell == nil) {
      _cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault    
      reuseIdentifier:CellIdentifier];

    //add link image to cell
        _cell.sharingPanel.a_shareButton.image = [UIImage imageNamed:@"button1"];
        _cell.sharingPanel.b_shareButton.image = [UIImage imageNamed:@"button2"];

  return _cell;
 }

In my custom view class I have the properties Lazyily initialised

- (UIImageView *)a_shareButton {

   if (!_a_shareButton) {

    _a_shareButton = [[UIImageView alloc]init];
    _a_shareButton.frame = CGRectMake(0,0,20,40); 
    [self addSubview:_a_shareButton];
    return _a_shareButton;
  }
return _a_shareButton;

}

1

There are 1 best solutions below

0
On

Not sure this is the best way of doing things but I am using KVO on the image property of my share button UIImagview. When this is updated, within the uiview custom class I am updating the frame property of the UIImageview

- (UIImageView *)a_shareButton {

if (!_a_shareButton) {
    _a_shareButton = [[UIImageView alloc]init];
    _a_shareButton.uiTag = A_BUTTON;
    [self addSubview:_a_shareButton];
 }
  return _a_shareButton;
}


 - (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    [self addObserver:self
                   forKeyPath:@"a_shareButton.image"
                      options:0 context:nil];
    }
  return self;
  }

   - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary  
   *)change context:(void *)context {

    _a_shareButton.frame = CGRectMake(0, 0,          
    _a_shareButton.image.size.width, _a_shareButton.image.size.height);

   }