UITableViewCell中的2个标签,无需自定义单元格

时间:2014-02-27 01:34:46

标签: ios uitableview

我想在一个单元格中放置两个文本标签。我使用Json来显示来自服务器的数据,我想显示第一个标题,然后是下面的文本(不是副标题)。

这是我的代码:

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


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    City * cityObject;
    cityObject = [ citiesArry objectAtIndex:indexPath.row];
    cell.textLabel.text = cityObject.cityState;
    cell.textLabel.text = cityObject.cityPopulation;
}

3 个答案:

答案 0 :(得分:3)

是否在故事板或NIB中设计了单元格?如果是这样,您可以将该单元格样式设置为字幕,或者将两个标签添加到contentView。为它们分配唯一标记,以便您可以在cellForRowAtIndexPath:方法中查询它们并设置它们的文本。

如果您没有故事板或NIB设计单元格,那么类似下面的内容应该有效。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

   static NSString *CellIdentifier = @"CustomCell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

   // Configure the cell...

   City * cityObject;
   cityObject = [ citiesArry objectAtIndex:indexPath.row];
   cell.textLabel.text = cityObject.cityState;
   cell.detailTextLabel.text = cityObject.cityPopulation;
}

答案 1 :(得分:1)

这个很好很简单..

只需创建两个标签并将其添加到单元格视图中。例如..

UILabel* label1 = [[UILabel alloc] initWithFrame:(CGRectMake(0, 0, 10, 50))];
    label1.text = cithObject.cityState;
    [cell addSubview:label1];

    UILabel* label2 = [[UILabel alloc] initWithFrame:(CGRectMake(0, 0, 10, 50))];
    label2.text = cityObject.cityPopulation;
[cell addSubview:label2];

答案 2 :(得分:0)

你可以在你的 - (UITableViewCell *)tableView中添加这段代码:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath:

    cell.detailTextLabel.text = cityObject.cityPopulation;

详细信息,请阅读 https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7