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

时间:2013-12-24 06:59:47

标签: ios uitableview nsdictionary

我正在解析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 个答案:

答案 0 :(得分:3)

而不是在customcell类中设置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;
}