1

我尝试为我的 listView 中的书签功能创建一个带有 3 个标签、名称、书籍和章节的自定义 UIView。现在我希望标签位于 tableView 单元格中的不同行中。如果您查看下面的代码,哪种方法是最好的方法,或者您会怎么做才能在自己的行上制作标签?我是 Objective C 和 Iphone 开发的新手。

结果在每个单元格的列表中应如下所示:

--------
name

book

chapter
--------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"BookmarkCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Bookmark *item = [self.items objectAtIndex:indexPath.row];

NSArray *chunks = [item.name componentsSeparatedByString: @","];

NSString *name;
NSString *book;
NSString *chapter;

if ([chunks count] > 0)
{
    name = [chunks objectAtIndex:0];
    if ([chunks count] > 1)
    {
        book = [chunks objectAtIndex:1];
        if ([chunks count] > 2)
        {
            chapter = [chunks objectAtIndex:2];
        }
    }
}

UIView * pNewContentView= [[UIView alloc] initWithFrame:cell.contentView.bounds];
CGRect labelFrame= pNewContentView.bounds;
labelFrame.size.width= labelFrame.size.width * 0.25;

UILabel* pLabel1=[[UILabel alloc] initWithFrame:labelFrame];
[pNewContentView addSubview:pLabel1];

labelFrame.origin.x= labelFrame.size.width;
UILabel* pLabel2=[[UILabel alloc] initWithFrame:labelFrame];
[pNewContentView addSubview:pLabel2];

labelFrame.origin.x= labelFrame.origin.x + labelFrame.size.width;
UILabel* pLabel3=[[UILabel alloc] initWithFrame:labelFrame];
[pNewContentView addSubview:pLabel3];

[cell.contentView addSubview:pNewContentView];

[pLabel1 setText:(name)];    
[pLabel2 setText:(book)];  
[pLabel3 setText:(chapter)];       

//cell.textLabel.text = name;
//cell.detailTextLabel.text = book;

return cell;
}
4

2 回答 2

5

全部替换xywidthheight检查输出并调整标签的高度和宽度以满足您的要求。

于 2012-08-28T12:01:23.373 回答
1

也许您在 Interface Builder 中创建自定义单元格然后在 cellForRowAtIndexPath 中设置您的单元格会更容易,有很多关于此的演示教程。

如果您想以编程方式执行此操作,那么它应该如下所示:

UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(10,15,300,20)];
name.text = @"some name";
UILabel *book = [[UILabel alloc] initWithFrame:CGRectMake(10,25,300,20)];
book.text = @"some book";
UILabel *chapter = [[UILabel alloc] initWithFrame:CGRectMake(10,35,300,20)];
chapter = @"chapter";

[cell.contentView addSubview:name];
[cell.contentView addSubview:book];
[cell.contentView addSubview:chapter];
于 2012-08-28T12:09:49.353 回答