0

コンテンツの量に基づいてUITableViewCellsをスケーリングするにはどうすればよいですか?私のセルでは、フォーラムを表す3つのラベルを使用しています。ラベルには、「エイリアス」、「日付」、および「コメント」という名前が付けられています。3番目のラベルのコメントは、任意の数のサイズにすることができます。したがって、「コメント」ラベルの大きさに応じて、セルを動的に作成する必要があります。以下は私の関連コードです:

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

Feedback *item = [self.items objectAtIndex:indexPath.row];

UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];

[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate    dateWithTimeIntervalSince1970:(double)item.time]]];

commentLabel.numberOfLines = 0;
[commentLabel sizeToFit];

CGSize textHeight = [commentLabel.text sizeWithFont:commentLabel.font  constrainedToSize:CGSizeMake(maxWidth, lineHeight *    commentLabel.numberOfLines)lineBreakMode:UILineBreakModeWordWrap];

return cell;
}

ご覧のとおり、commentsLabelの高さはtextHeightで設定しています。しかし、私はこれから何をしますか?ラベルの高さがわかっている場合、commentLabelの高さに応じてセルの高さを設定するにはどうすればよいですか。私のコードに基づいたコード例を教えてください。次の方法を使用する必要があると思いますが、その方法がわかりません。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

}
4

2 に答える 2

6

このメソッドを使用して、テキストの高さを取得します

-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{

CGSize maximumSize = CGSizeMake(labelWidth, 10000);

//provide appropriate font and font size
CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:@"Trebuchet MS" size:13.0f]
                         constrainedToSize:maximumSize
                             lineBreakMode:UILineBreakModeTailTruncation];
return labelHeighSize.height;
}

このメソッドは、渡すテキストの高さを返します。このメソッドをクラスに追加します。また、 tableView:heightForRowAtIndexPath:デリゲート メソッドを使用して、各セルの高さを設定します。

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   Feedback *item = [self.items objectAtIndex:indexPath.row];

   CGFloat textHeight = [self getLabelHeightForText:item.comment andWidth:162];//give your label width here
    return textHeight;
}    

これで問題は解決できると思います。

于 2012-10-29T15:06:13.430 に答える
0

実装で Label 宣言を行うことができます。

@implementation pTableView
{
    UILabel *aliasLabel;
}

次に、行の高さで、デフォルトの Height (44) + aliasLabel.Height を使用できます

return 44 + aliasLabel.frame.size.height;

次に、テーブル内のラベルを区別する必要がある場合

aliasLabel.tag = indexpath.row
于 2012-10-29T15:06:30.120 に答える