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

xすべてをywidthに置き換えますheight。出力を確認し、要件を満たすようにラベルの高さと幅を調整します。

于 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 に答える