LoginSignup
19
20

More than 5 years have passed since last update.

xibでカスタムセルを作成し、UIGestureRecognizerを利用したら躓いた

Last updated at Posted at 2014-05-29

簡単に解決できそうで、中々手間取ったので回避策を残します。

環境

  • xcode 5.1.1
  • iOS SDK 7.1

つまづいたこと

xibでUITableViewCellのカスタムセルを作成し、その中で
UIGestureRecognizerを利用したら、[tableView dequeueReusableCellWithIdentifier:@"MyCell"];の呼び出しで、下記の例外が発生した。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier (MyCell) - nib must contain exactly one top level object which must be a UITableViewCell instance'


-(void)initCustomCell {
    UINib* nib = [UINib nibWithNibName:@"MyCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"MyCell"];
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell* cell = (MyCell*)
    [tableView dequeueReusableCellWithIdentifier:@"MyCell"]; // ここで例外発生
    return cell;
}

原因?

 エラーメッセージによると、nibのトップレベルオブジェクトはUITableViewCellである必要があるらしい。UIGestureRecognizerをxibに登録した事により、トップレベルオブジェクトがUIGestureRecognizerになってしまったため、例外が発生するようになったっぽい。
(実際にnibをロードして先頭オブジェクトを確認したら、UIGestureRecognizerオブジェクトになっていた)

スクリーンショット 2014-05-29 20.14.52.png

回避策

セルのロード方式を旧式にして、さらにnib内のオブジェクトにカスタムセルが出るまで探索する。。。。

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell* cell = (MyCell*)
    [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
    if( cell == nil ) {
        NSArray* nibArray = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:nil options:nil];
        for(id obj in nibArray) {
            if( [obj isMemberOfClass:[MyCell class]] ) {
                cell = (MyCell*)obj;
                break;
            }
        }
    }
    return cell;
}

参考

19
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
20