48

xibをリンクしたサブクラスを作成しようとしUICollectionViewCellています。これを実行します。新しいxibファイルを作成し、それにを追加してから、次のUICollectionViewCellサブクラスファイルを作成します。

@interface MyCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UILabel *label;
@end

また、ファイル所有者のカスタムクラスMyCellでインターフェイスビルダーのクラスをリンクし、を追加してUILabelから、UICollectionViewviewDidLoadで次のようにします。

[self.collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];

UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"MyCell"];

これと同様に:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];


cell.label.text = @"Cell Text";


return cell;
}

ただし、これは機能しません。次のエラーが発生します。

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x907eca0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.'

私は何を間違えましたか?UICollectionViewCellサブクラスをxibに接続し、それを?に表示するにはどうすればよいUICollectionViewですか?

編集:

私はこれをしました:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

NSString *identifier = @"MyCell";

static BOOL nibMyCellloaded = NO;

if(!nibMyCellloaded)
{
    UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
    [cv registerNib:nib forCellWithReuseIdentifier:identifier];
    nibMyCellloaded = YES;
}

MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];


cell.labelCell.text = @"Text";


return cell;
}
4

2 に答える 2

48

.xibファイルのセルがセルのタイプを認識していることを確認してください。

InterfaceBuilderでセルを選択します

ここに画像の説明を入力してください

次に、IDインスペクターで

ここに画像の説明を入力してください

その後、ラベルをプロパティに関連付けます。(私はあなたがすでにそれをしたと思います)

cellForItemAtIndexPath:次に、メソッドに.xibファイルがすでにロードされているかどうかを確認することをお勧めします

NSString *identifier = @"MyCell";    

    static BOOL nibMyCellloaded = NO;

    if(!nibMyCellloaded)
    {
        UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil];
        [cv registerNib:nib forCellWithReuseIdentifier:identifier];
        nibMyCellloaded = YES;
    }
于 2013-01-22T21:03:35.553 に答える
20

答えは、UICollectionCellを追加するこのドキュメントUICollectionViewにあります。

StoryBoard内のUICollectionViewのみがUICollectionViewCellを内部に持っています。XIBを使用する場合は、CellName.xibを使用して新しいXIBを作成し、それにCollectionViewCellを追加して、UICollectionViewカスタムクラスの名前を指定します。その後、registerNib.Sampleコードを使用します:https ://github.com/lequysang/TestCollectionViewWithXIB

于 2013-05-22T14:02:27.103 に答える