如何在没有自定义单元格的情况下在UITableViewCell中封装文本 [英] How do I wrap text in a UITableViewCell without a custom cell
问题描述
这是在iPhone 0S 2.0。 2.1的答案也很好,虽然我不知道有关表的任何差异。
This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.
感觉像应该可以得到文本换行不创建自定义单元格,因为默认情况下 UITableViewCell
包含 UILabel
。我知道如果我创建一个自定义单元格,我可以使它工作,但这不是我想实现 - 我想知道为什么我目前的方法不工作。
It feels like it should be possible to get text to wrap without creating a custom cell, since a UITableViewCell
contains a UILabel
by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.
我发现标签是按需创建的(因为单元格支持文本和图片访问,所以如果我这样做,就不会创建数据视图):
I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:
cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];
那么我得到一个有效的标签,但是设置 numberOfLines
(和lineBreakMode)不工作 - 我仍然得到单行文本。在 UILabel
中有足够的高度来显示文本 - 我只是在 heightForRowAtIndexPath $ c中返回一个大的值$ c>。
then I get a valid label, but setting numberOfLines
on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the UILabel
for the text to display - I'm just returning a large value for the height in heightForRowAtIndexPath
.
推荐答案
这里有一个更简单的方法,它适用于我:
Here is a simpler way, and it works for me:
在 cellForRowAtIndexPath:
函数中。第一次创建您的单元格:
Inside your cellForRowAtIndexPath:
function. The first time you create your cell:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}
您会注意到我将标签的行数设置为0 。
You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.
下一部分是指定你的 UITableViewCell
将在 heightForRowAtIndexPath
函数中执行:
The next part is to specify how large your UITableViewCell
will be, so do that in your heightForRowAtIndexPath
function:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = @"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
我添加了20到我返回的单元格高度,因为我喜欢在我的文本。
I added 20 to my returned cell height because I like a little buffer around my text.
这篇关于如何在没有自定义单元格的情况下在UITableViewCell中封装文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!