How do you load custom UITableViewCells from Xib files?

前端 未结 23 1749
抹茶落季
抹茶落季 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:22

    I dont know if there is a canonical way, but here's my method:

    • Create a xib for a ViewController
    • Set the File Owner class to UIViewController
    • Delete the view and add an UITableViewCell
    • Set the Class of your UITableViewCell to your custom class
    • Set the Identifier of your UITableViewCell
    • Set the outlet of your view controller view to your UITableViewCell

    And use this code:

    MyCustomViewCell *cell = (MyCustomViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
      UIViewController* c = [[UIViewController alloc] initWithNibName:CellIdentifier bundle:nil];
      cell = (MyCustomViewCell *)c.view;
      [c release];
    }
    

    In your example, using

    [nib objectAtIndex:0]
    

    may break if Apple changes the order of items in the xib.

    0 讨论(0)
  • 2020-11-22 11:22
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
                let cellReuseIdentifier = "collabCell"
                var cell:collabCell! = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? collabCell
                if cell == nil {
                    tableView.register(UINib(nibName: "collabCell", bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
                    cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! collabCell!
                }
    
    
                return cell
    
    }
    
    0 讨论(0)
  • 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:     '[<MyUITableViewController 0x6a383b0> 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.
    0 讨论(0)
  • 2020-11-22 11:27
    1. Create your own customized class AbcViewCell subclass from UITableViewCell (Make sure your class file name and nib file name are the same)

    2. Create this extension class method.

      extension UITableViewCell {
          class func fromNib<T : UITableViewCell>() -> T {
              return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)?[0] as! T
          }
      }
      
    3. Use it.

      let cell: AbcViewCell = UITableViewCell.fromNib()

    0 讨论(0)
  • 2020-11-22 11:29

    First import your custom cell file #import "CustomCell.h" and then change the delegate method as below mentioned:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"CustomCell";
    
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }         
    
         return cell;
    }
    
    0 讨论(0)
  • 2020-11-22 11:30

    Correct Solution is this

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CustomCell"];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
        return cell; 
        }
    
    0 讨论(0)
提交回复
热议问题