2013-12-12 97 views
0

我试图寻找初始化其放置在自定义UITableCell延迟实例化的UIImageView

我的自定义视图中有一个以上的按键自定义UIView类中的UIImageViews的最有效方式。实质上,我试图复制从单元格内设置UIImageviews的标准方式。目前我尝试创建UIImageview,但UIImageView的图像属性为null。如果我第二次调用getter,则不是。

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

+1 @JesseRusak我唯一要补充的是,你不需要在条件内使用'return'。无论如何,你的代码所做的下一件事是返回。 – ChrisH

+0

你的tableView代码中也有不平衡的括号,但我猜这是一个错误 – ChrisH

回答

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

    }