2013-10-13 33 views
3

我想動態調整一個UITableViewCell裏面的UIImage的寬度,我使用故事板來設計UITableViewCell,我只是添加了一個標籤和一個圖像,屬性得到正確更新,我甚至將寬度的值加載到標籤中以顯示它是正確的值,對於圖像,我加載了一個我想重複的背景圖像,但圖像不會最初更新寬度,如果我向上和向下滾動,圖像顯示爲預期的,這裏是對的cellForRowAtIndexPath的代碼,我也試着穿上willDisplayCell方法的代碼,相同的結果UITableViewCell與UIImage,寬度不更新在初始顯示的單元

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycustomcell"]; 
    int r = [[data objectAtIndex:indexPath.row] intValue]; 
    UIImageView *img = (UIImageView *)[cell viewWithTag:2]; 
    img.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"some_img" ofType:@"png"]]]; 
    CGRect frame = img.frame; 
    frame.size.width = r*16; 
    img.frame = frame; 

    int n = img.frame.size.width; 
    UILabel *label = (UILabel *)[cell viewWithTag:1]; 
    label.text = [NSString stringWithFormat:@"custom %d", n]; 
    [cell setNeedsDisplay]; 
    return cell; 
} 

我只想要th最初工作是因爲它在滾動後工作,想法?

+0

您是否在故事板中啓用了Auto Layout? –

+0

您從不創建單元格 – vikingosegundo

+0

@vikingosegundo如果使用單元格原型,則不必創建單元格。 'dequeueReusableCellWithIdentifier'將爲你創建它。 – Rob

回答

7

tableview單元格內容的動態調整大小是一個衆所周知的問題。雖然有缺憾的解決方法,我認爲正確的解決方案取決於您是否使用自動佈局與否:

  • 如果使用自動佈局,確保您單元的圖像視圖的寬度限制,然後你可以改變約束的constant

    for (NSLayoutConstraint *constraint in img.constraints) 
    { 
        if (constraint.firstAttribute == NSLayoutAttributeWidth) 
         constraint.constant = r*16; 
    } 
    

    坦率地說,我寧願使用自定義UITableViewCell子類,並有寬度限制的IBOutlet(如imageWidthConstraint),並從具有通過約束來列舉找到正確的爲您節省一個,你可以簡單地:

    cell.imageWidthConstraint.constant = r*16; 
    
  • 如果不使用自動佈局,你應該繼承UITableViewCell,請使用您的電池原型的基類,然後覆蓋layoutSubviews,並調整圖像視圖那裏。請參閱Changing bounds of imageView of UITableViewCell

無論哪種方法你採用,使用UITableViewCell子類,無需使用viewForTag結構,這使得視圖控制器代碼更直觀一點。

+2

這應該是真正被接受的答案,而不是從原始海報到只刪除自動佈局。 – Michael

+0

很好的答案,像魅力一樣工作。 – swebal

+0

這確實應該是正確的答案。刪除自動佈局不是一種選擇,它可能導致更嚴重的問題。 –