How do you load custom UITableViewCells from Xib files?

前端 未结 23 1738
抹茶落季
抹茶落季 2020-11-22 11:11

The question is simple: How do you load custom UITableViewCell from Xib files? Doing so allows you to use Interface Builder to design your cells. The answer app

23条回答
  •  名媛妹妹
    2020-11-22 11:23

    I used bentford's Method #2:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
        if (cell == nil) {
            // Load the top-level objects from the custom cell XIB.
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BDCustomCell" owner:self options:nil];
            // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
            cell = [topLevelObjects objectAtIndex:0];
        }
    
        return cell;
    }
    

    It works, but watch out for connections to File's Owner in your custom UITableViewCell .xib file.

    By passing owner:self in your loadNibNamed statement, you set the UITableViewController as File's Owner of your UITableViewCell.

    If you drag and drop to the header file in IB to set up actions and outlets, it will set them up as File's Owner by default.

    In loadNibNamed:owner:options, Apple's code will try to set properties on your UITableViewController, since that's the owner. But you don't have those properties defined there, so you get an error about being key value coding-compliant:

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

    If an Event gets triggered instead, you'll get an NSInvalidArgumentException:

    -[MyUITableViewController switchValueDidChange:]: unrecognized selector sent to instance 0x8e9acd0
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyUITableViewController switchValueDidChange:]: unrecognized selector sent to instance 0x8e9acd0'
    *** First throw call stack:
    (0x1903052 0x15eed0a 0x1904ced 0x1869f00 0x1869ce2 0x1904ec9 0x5885c2 0x58855a 0x62db76 0x62e03f 0x77fa6c 0x24e86d 0x18d7966 0x18d7407 0x183a7c0 0x1839db4 0x1839ccb 0x1f8b879 0x1f8b93e 0x585a9b 0xb904d 0x2c75)
    terminate called throwing an exceptionCurrent language:  auto; currently objective-c
    

    An easy workaround is to point your Interface Builder connections at the UITableViewCell instead of File's Owner:

    1. Right click on File's Owner to pull up the list of connections
    2. Take a screen capture with Command-Shift-4 (drag to select the area to be captured)
    3. x out the connections from File's Owner
    4. Right click on the UITableCell in the Object hierarchy and re-add the connections.

提交回复
热议问题