2013-12-12 115 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); 

    }