2012年4月19日 星期四

根據內容多寡,調整cell高度

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

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


cell.textLabel.text=[[theArray objectAtIndex:indexPath.row] objectForKey:@"description"];
cell.textLabel.lineBreakMode=UILineBreakModeTailTruncation; //若內容超出cell可容納範圍,最後出現"..."
cell.textLabel.numberOfLines=30; //單一cell出現的行數,0為無限

return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [[theArray objectAtIndex:indexPath.row] objectForKey:@"description"];

//開始去計算全部內容,以字體大小14、lineBreakMode:UILineBreakModeTailTruncation狀態下,會得到多少的範圍寬高度
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeTailTruncation];
//CGSizeMake(240.0, 480.0) 設定單一cell最大的寬高度,若得到的size超過這個範圍,則只會以這個為基準;

return MAX(size.height + 10, 40.0f); //單一cell高度最小會為40

}



沒有留言:

張貼留言