Add UITableView with dynamic content in an XIB file

Is there a way to add a UITableView (not a Table View Controller , but a TableView within another view ) and set its content to "Dynamic Prototype" in an XIB file ?

This works fine when adding a UITableView in a view controller within the storyboard . However, when I try to do the same in an XIB file, I cannot set its content to "Dynamic Prototype" .


Not 100% sure on this, but I don't think there is a way to set the UITableView content to "Dynamic Prototype" in a XIB file.

However you can achieve the same functionality by creating another XIB file, called something like "MyTableViewCell.xib", that only contains a UITableViewCell, give the cell an identifier, go to File's Owner and in the identity inspector set it to the same view controller class as your table view xib, then create an IBOutlet in your view controller like this:

 @property (nonatomic, assign) IBOutlet UITableViewCell *customCell;

then in the XIB, click on the File's Owner and control-drag to the uitableviewcell and set the cell's outlet to the "customCell" property.

(This might be done a lot easier if you find the button that looks like a play button inside a circle in the bottom left hand corner of the graphic editor, click on it, then do your dragging in that column).

After all that, in cellForRowAtIndexPath use code similar to this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = @"CustomCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell" owner:self options:nil];

        cell = customCell;
    }

    // Other cell configurations....
}

Hope that makes sense and suits your needs!


Update

Please be aware of a gotcha where if you resize the tableview; the xml will be regenerated by Xcode and require you to re-add the attribute. I have confirmed that this edit still works in version 9.3+. A sample stub is available at https://github.com/mingsai/test-stub-tableviewdynamic-inxib.git.

Original Answer

  • Open the file navigator
  • Right-click on the YourCustomView.xib file
  • Open As > Source Code
  • openas

  • Find the XML beginning with

    tableview中的XML

  • Within the XML tableview tag locate the style attribute
  • Leaving an empty space before the style tag, paste in dataMode="prototypes"
  • 链接地址: http://www.djcxy.com/p/68176.html

    上一篇: 表单验证忽略空值

    下一篇: 在XIB文件中添加带有动态内容的UITableView