如何将标签放入表格单元格?

时间:2011-07-22 12:52:00

标签: objective-c ios cocoa-touch uitableview uilabel

table cell http://img543.imageshack.us/img543/4315/28749523.png

这是我要制作的单元格,左边是cell.text,右边是标签。 现在表格样式是

UITableViewStyleGrouped当我尝试制作标签时,我会写下这些代码。

cell.textLabel.text = @"All";
UIView* view = cell.contentView;
UILabel* label1 = [[UILabel alloc] initWithFrame:cell.frame];
label1.textColor = [UIColor blackColor];
label1.textAlignment = UITextAlignmentCenter;
label1.text = @"%15";
[view addSubview:label1];
[label1 release];

但这不起作用,因为标签的单元格覆盖了一个又一个。任何人都可以帮助我用代码来制作这种外观。

3 个答案:

答案 0 :(得分:3)

代码中的问题似乎是 label1的框架。像下面一样更改其框架。

CGRect lFrame = CGRectMake(cell.frame.width - 100, 0, 100, cell.frame.height);
UILabel* label1 = [[UILabel alloc] initWithFrame:lFrame];

使用现有样式:您正在使用的样式已预定义。无需将自定义标签添加到单元格。您可以通过将表格单元格的样式指定为 UITableViewCellStyleValue1 来实现此样式。

[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 ....

您可以更改单元格的 textLabel detailedTextLabel 的样式,颜色和大小等字体属性,以满足您的需求。

答案 1 :(得分:2)

如果满足您的需求,预定义的样式就很棒。

否则像这样的方法适用于您需要更多布局功能或单元格中更多视图的情况:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [self makeCell: CellIdentifier];
    }

    MyData *data =  [self.data objectAtIndex:indexPath.row];

    UILabel *lbl1 = (UILabel *)[cell viewWithTag:1];
    UILabel *lbl2 = (UILabel *)[cell viewWithTag:2];

    lbl1.text = data.text;
    lbl2.text = data.auxText;    

    return cell;
}


- (UITableViewCell *)makeLensListCell: (NSString *)identifier
{
    CGRect lbl1Frame = CGRectMake(10, 0, 140, 25);
    CGRect lbl2Frame = CGRectMake(10, 150, 140, 25);

    UILabel *lbl;

    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];

    // Label with tag 1.
    lbl = [[UILabel alloc] initWithFrame:lbl1Frame];
    lbl.tag = 1;
    [cell.contentView addSubview:lbl];
    [lbl release];

    // Label with tag 2.
    lbl = [[UILabel alloc] initWithFrame:lbl2Frame];
    lbl.tag = 2;
    lbl.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:lbl];
    [lbl release];

    // Add as many labels and other views as you like

    return cell;
}

答案 2 :(得分:1)

只需将您的UITableviewCell类型设置为UITableViewCellStyleValue1,并执行以下操作。

cell.textLabel.text = @"All";
cell.detailTextLabel.text = @"%15";

根本不需要在单元格中添加视图。此外,您可以在使用UILabel更改时随意更改textLable和DetailTextLabel属性。他们是UILabel本身。因此,无论您使用UILabel做什么,都可以做任何事情。

希望得到这个帮助。

相关问题