我正在解析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];
而不是在customcell类中设置lebel.text,而是将其添加到中cellForRowAtIndexPath
。
在customcell.h
文件中创建标签的属性
@property (nonatomic, weak) IBOutlet UILabel *label;
并在customcell.m
文件synthesys中。
@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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句