【问题标题】:UITableViewCell to display long texts in cell.textLabelUITableViewCell 在 cell.textLabel 中显示长文本
【发布时间】:2014-02-09 14:37:16
【问题描述】:
如果我有一个长文本,我必须增加单元格大小以适应文本。
当我分配:cell.textLabel.text = @"my string" 时,如果字符串很长,它会被截断。
在这种情况下,如何在两行或多行中显示文本?我只使用UITableViewCell,而不是在任何地方对其进行子类化。是否有一些代码可以直接使用cell.textLabel 显示长文本?我不是在谈论向单元格添加单独的视图。
【问题讨论】:
标签:
ios
objective-c
uitableview
uilabel
【解决方案1】:
cell.textLabel 不允许您将字符串换行成两行。您需要做的是自定义它,将您自己的 UILabel 添加到 UITableViewCell 并定义其参数。
这是一个可以添加到 TableView 中的工作代码。
//define labelValue1 in your .h file
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(@"Inside cellForRowAtIndexPath");
static NSString *CellIdentifier = @"Cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// If no cell is available, create a new one using the given identifier.
if (cell == nil)
{
// Use the default cell style.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
labelValue1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
labelValue1.font = [UIFont fontWithName:@"BradleyHandITCTT-Bold" size: 23.0];
labelValue1.textColor = [UIColor whiteColor];
labelValue1.textAlignment = NSTextAlignmentCenter;
labelValue1.numberOfLines = 2; //note: I said number of lines need to be 2
labelValue1.backgroundColor = [UIColor clearColor];
labelValue1.adjustsFontSizeToFitWidth = YES;
labelValue1.tag = 100;
[cell.contentView addSubview:labelValue1];
}
else
{
labelValue1 = (UILabel *) [cell viewWithTag:100];
}
// Set up the cell.
NSString *str1 = [arryData3 objectAtIndex:indexPath.row];
labelValue1.text = str1;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
【解决方案2】:
可以显示多行
cell.textLabel.LineBreakMode = NSLineBreakByWordWrapping
【解决方案3】:
这是给 Swift 的。
cell.textLabel?.numberOfLines = 10 /// or the number you like.