2013-06-21 87 views
4

我正在嘗試更改UITextView的高度,我在自定義單元格中爲我的tableView創建了一個UITextView。在cellForRowAtIndexPath中更改UITextView的高度

'OverviewCell'是此自定義單元格在筆尖中的標識符,同時UITextView'postIntro'也被拖入筆尖中。令人遺憾的是,身高並沒有改變,只有在我滾動身高後才改變。它無需滾動可見的細胞是剛剛從筆尖的默認高度。

當我嘗試更改'postImage'的高度時,會發生同樣的問題。

這是我的代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"OverviewCell"; 

    OverviewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    Post *post = [self.posts objectAtIndex:[indexPath row]]; 

    if(!cell) 
    { 
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"OverviewCell" owner:nil options:nil]; 

    for(id currentObject in topLevelObjects) 
    { 
     if([currentObject isKindOfClass:[OverviewCell class]]) 
     { 
      cell = (OverviewCell *)currentObject; 
      break; 
     } 
    } 
    } 

    [[cell postImage] setImage:[UIImage imageWithData:post.image]]; 
    [[cell postTitle] setText:post.title]; 
    [[cell postIntro] setText:post.intro]; 

    // Resize the intro textview so the text fits in. 
    CGRect frame = cell.postImage.frame; 
    frame.size.height = 20; //cell.postIntro.contentSize.height; 
    [cell.postIntro setFrame:frame]; 

    NSLog([NSString stringWithFormat:@"Height of textView on indexpath %i is set to %f", indexPath.row ,cell.postImage.frame.size.height]); 

    return cell; 

} 

任何其他建議我的代碼,歡迎...

回答

2

我終於得到它改變的UITextView的約束代碼工作。

我已創建並附加到UITextview約束的IBOutlet。

IBOutlet NSLayoutConstraint * postContentHeightConstraint; 

之後,我給自己定的約束條件高度爲單元(contentSize)指定的高度。

self.postContentHeightConstraint.constant = self.postContent.contentSize.height; 

新的高度設置爲約束後,呼籲UITextView的

[self.postContent layoutIfNeeded]; 
+1

我有同樣的問題。我修正它的方式是繼承'UITableViewCell',覆蓋'drawRect:'方法,並將UITextView的高度設置爲'textView.contentSize.height'。我已經有了'UITableViewCell'子類,但如果這就是你所需要的,你可能只需要子類「UITextView」。 –

0

實現你的表視圖委託tableView:heightForRowAtIndexPath:

更新:要更新的UITextView的高度,它已被創建之後,調用[cell.postIntro setNeedsLayout]設置框架

+0

的layoutIfNeeded功能,此功能已經存在。即調整其工作正常細胞的高度。我只是想改變單元格內的「UITextView」的高度(每個單元格不同) –

+0

@ R.Schaaphuizen啊我看到了。看到我更新的答案。 – Turch

+0

仍然沒有工作,它只是改變了afters我向下滾動,並再次備份。 –

0

爲了改變UITextView的高度後,打電話

[tableView beginUpdates]; 
[tableView endUpdates]; 

設置後對於新的UITextView尺寸。

問題thisthis將幫助您解決問題。

希望的答案幫助!