如何在iOS中设置tableView单元格标题?

3

我正在解析JSON并将其存储在数组中。我有一个自定义的单元格子类,我试图从已解析的JSON内容设置标签的标题。 以下是解析过程。

@implementation BlogScreenViewController    
 - (void)viewDidLoad
{
 [super viewDidLoad];
  self.jsonArray = [[NSMutableArray alloc]init];

 NSError *error = nil;
 NSURL *url = [NSURL URLWithString:@"http:web_services/blog.php"];
 NSData *data = [NSData dataWithContentsOfURL:url];
 self.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
 for (NSDictionary *obj in self.jsonArray)    
{
    NSLog(@"JSON string output :- %@ ", [obj objectForKey:@"titre"]); // shows titles
}

在自定义单元格子类中
    // set blog title label
    UILabel *blogTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 20, 200, 20)];
   // blogTitleLabel.text = @"This is blog title";  // This shows properly if used. 

    for (NSDictionary *obj in blogScreenVC.jsonArray ) //This doesn't work.
    {
         blogTitleLabel.text = [NSString stringWithFormat:@"%@",[obj objectForKey:@"titre"]];
    }
    [blogTitleLabel setFont:[UIFont systemFontOfSize:9]];
    [self addSubview:blogTitleLabel];

1
请清楚地表达您的问题。您的问题标题提到了TableView的标题,但是在问题正文中却谈到了单元格的名称?请清晰地描述一些细节。 - Mani
在自定义单元格类中,将自定义单元格标签对象作为属性synthesize,并在您的表视图委托方法中使用该对象。 - Romance
@Romance - 你的方法有示例代码吗? - icodes
好的,我尝试了这个…… for (NSDictionary *obj in self.jsonArray ) { cell.blogTitleLabel.text = [NSString stringWithFormat:@"%@", [obj objectForKey:@"titre"]]; } 仅显示数组中的一个标题...但是数组的NSLog显示更多 - icodes
2
@icodes,请查看以下答案,该答案由dilep回答。按照这些步骤操作可以解决您的问题。 - Romance
显示剩余6条评论
1个回答

3

不要在自定义单元格类中设置 lebel.text,而是将其添加到 cellForRowAtIndexPath 中。

customcell.h 文件中创建标签的属性。

@property (nonatomic, weak) IBOutlet UILabel *label;

customcell.m文件中综合它。
@synthesize label = _label;

在你的viewcontroller.m文件中

#import "CustomCell.h"

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

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) 
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    } 

    if (self.jsonArray.count !=0) {
      NSMutableDictionary * tmpDictn = [self.jsonArray objectAtIndex:indexPath.row];
      if ([tmpDictn objectForKey:@"titre"] != nil)
        {
          cell.label.text = [tmpDictn objectForKey:@"titre"];
        }else{
          cell.label.text = @"tmpDictn does not contain data";
        }
    }else{
          cell.label.text = @"jsonArray does not contain data";
    }

    return cell;
}

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