我需要创建一个UITableView,其中UITableViewCell包含两个UILabel,其中一个应该适合其内容NSString的高度。 UILabel的宽度是固定的,行数设置为0.如何获得高度? 我看到这样的代码:
CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont
constrainedToSize:maximumSize
lineBreakMode:self.myLabel.lineBreakMode];
但结果是:UILabel中只有一个字符。 为什么我不能使用这种方法?非常感谢你!
答案 0 :(得分:1)
试试这个
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = @"This is a very very long string which wraps";
CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:UILineBreakModeWordWrap];
return size.height + 10;
}
答案 1 :(得分:1)
我终于让它工作了,代码在我的项目中:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"shopmessage";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel* content = (UILabel*)[cell viewWithTag:11];
UILabel* date = (UILabel*)[cell viewWithTag:12];
NSDictionary* msg = [ _msglist objectAtIndex:indexPath.row];
NSString* type = [[msg objectForKey:@"msgtype"] intValue] == 0 ? @"我:":@"店家:";
[content setText:[NSString stringWithFormat:@"%@%@",type,[msg objectForKey:@"sendmsg"]]];
[date setText:[msg objectForKey:@"sendtime"]];
CGSize contentsize = [content.text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(280, 1000) lineBreakMode:UILineBreakModeWordWrap];
// content.frame.size = contentsize;
content.frame = CGRectMake(content.frame.origin.x, content.frame.origin.y, contentsize.width, contentsize.height);
[date setText:[msg objectForKey:@"sendtime"]];
// date.frame.origin = CGPointMake(date.frame.origin.x, content.frame.origin.y + content.frame.size.height + 10);
date.frame = CGRectMake(date.frame.origin.x, content.frame.origin.y + content.frame.size.height, date.frame.size.width, date.frame.size.height);
return cell;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary* msg = [ _msglist objectAtIndex:indexPath.row];
NSString* text =[msg objectForKey:@"sendmsg"];
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(280, 1000) lineBreakMode:UILineBreakModeCharacterWrap];
return size.height + 30;
}