惰性实例化UIImageView



我正在努力寻找在自定义UIView类中初始化UIIMageViews的最有效方法,该类位于自定义UITableCell 中

我的自定义视图有多个按钮。从本质上讲,我正在尝试复制在单元格中设置UIImageview的标准方式。我目前尝试的方法是懒惰地创建UIImageview,但UIImageview的image属性为null。如果我第二次调用getter,它不是。

所以在我的表视图中

 - (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;
 }

在我的自定义视图类中,我有属性Lazyly初始化的

- (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;

}

不确定这是最好的方法,但我在共享按钮UIImagview的图像属性上使用了KVO。更新后,在uiview自定义类中,我将更新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);
   }

最新更新