iOS7上的表格视图副标题

8

我试图在我的表格视图单元格上添加副标题,但是它们没有显示出来。

问题出在哪里?

这一行代码[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle]是否与iOS 7保持最新?

祝好

Frank


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

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

    cell.textLabel.text = @"TestA";
    cell.detailTextLabel.text = @"TestB";

    return cell;
}

我觉得那看起来是正确的。你使用了Storyboard/Xib文件吗?确保在那里放置了一个单元格原型。 - Enrico Susatyo
你是说这段代码只会显示主标题,而不会显示每一行的副标题吗?这是全部都在代码中实现的还是使用了原型单元格? - rmaddy
4个回答

5
这段代码:
if (!cell)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

这段代码中的 dequeueReusableCellWithIdentifier:forIndexPath: 方法保证会分配一个新的单元格,因此它永远不会执行。

不幸的是,registerClass:forCellReuseIdentifier: 方法无法让你指定一个 UITableViewCellStyle

dequeueReusableCellWithIdentifier:forIndexPath: 方法改为简单的 dequeueReusableCellWithIdentifier:CellIdentifier。这个方法并不保证总能返回一个单元格。当没有可用单元格时,你的代码可以创建一个你想要的样式的新单元格。


* - (如果你使用故事板,则会像 rdelmar 所指出的那样,但本例不是这种情况。)


1
“这个方法并不保证一定会返回一个单元格”-- 不一定是真的。如果单元格在Storyboard中创建了,那么该方法也保证会返回一个单元格。 - rdelmar
如果您已经在tableView中注册了一个类或nib,它将自动返回其实例,cell永远不会为nil。 - estobbart

1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath        *)indexPath {
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil)
{ 
 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
cell.textLabel.text = @"Title1"; 

cell.detailTextLabel.text = @"Subtitle 1";

return cell;
}

答案应包括解决方案的描述。 - Enkode
在 Inspector 视图中为单元格分配一个标识符,并将以下代码编写在 cellForRowAtIndexPath 中,其中 cel.detailTextLabel.text 是副标题。 - Jamil

0

只需继承UITableViewCell并覆盖

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;

第一行

[super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];

并将您的单元格类与表视图注册

[tableView registerClass:[YourCellSubclass class] forCellReuseIdentifier:@"YourCellID"];

0

我曾经遇到了类似的问题,但是在网上找到的所有解决方案都无法解决。结果发现是我自己太蠢了。我会将我的解决方案发布出来,以防其他人遇到类似的情况。

我假设您正在使用storyboard,已经创建了一个原型并将样式设置为副标题

在您的storyboard的文档大纲中,请确保选择protoptype单元格并选择副标题。参见图片:

enter image description here


现在确保标签字体颜色与背景颜色形成对比!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接