截面行中有多个标签

时间:2013-11-06 10:33:17

标签: ios objective-c arrays uitableview

因为有几天我正在尝试打印来自数据数组的两个字符串,从来自我的服务器的xml文件解析(很长时间:D)。问题是我只能设法打印两个字符串中的一个。我做了我的研究并找到了技术指针,但如果有人可以帮助我,我无法设法完成技术工作。这是我的代码:

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

static NSString *MyIdentifier = @"MyIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
for(UIView *eachView in [cell subviews]){
    [eachView removeFromSuperview];
}

UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl1 setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
[lbl1 setTextColor:[UIColor grayColor]];
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
lbl1.text = [[stories objectAtIndex: storyIndex] objectForKey: @"creation_date"];
NSLog(lbl1.text);
[cell addSubview:lbl1];
[lbl1 release];

UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl2 setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
[lbl2 setTextColor:[UIColor blackColor]];
lbl2.text = [[stories objectAtIndex: storyIndex] objectForKey: @"name"];
NSLog(lbl2.text);
[cell addSubview:lbl2];
[lbl2 release];

//Used to do this ---> int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
//[cell.textLabel setText:[[stories objectAtIndex: storyIndex] objectForKey: @"creation_date"]];
return cell;

}

2 个答案:

答案 0 :(得分:1)

问题我看到的是你将子视图直接添加到单元格。您应该将它添加到cell.contentview,如下所示:

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    CGRect frame = CGRectMake(0, 0, 160, 50);
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.textAlignment = UITextAlignmentRight;
    [cell.contentView addSubview:label];
    [label release];
}

// Get a reference to the label here

label.text = @"9:00am";

return cell;
}

我也强烈建议为UITableViewCell创建子类。

答案 1 :(得分:0)

不要试图以这种方式为单元格动态创建标签,而是最好只使用已经根据需要放置两个标签的自定义表格视图单元格。然后,您可以直接为这些标签设置文本。

查看您的代码,我还建议您转到ARC而不是MRC,并阅读表格视图的文档;在这种情况下,您不需要检查从重用队列返回的nil值,或者您是否在故事板上使用了正确配置的自定义单元格。