懒惰的实例化UIImageView

时间:2013-12-12 17:50:22

标签: ios objective-c uiimageview lazy-initialization

我正在尝试查看在自定义UITiewCell中放置UIIMageViews的最有效方法,该类放在Custom UITableCell

我的自定义视图有多个按钮。本质上,我试图复制从单元格内设置UIImageviews的标准方法。我正在尝试的当前方式懒洋洋地创建UIImageview但是UIImageview的image属性为null。如果我第二次打电话给吸气剂则不是。

所以在我的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;
 }

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

- (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 个答案:

答案 0 :(得分:0)

不确定这是最好的做事方式,但我在分享按钮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);

   }