UITableView as a subview?

2020-07-23 03:45发布

Is this possible? I just want a small table in my current view... here is what I'm trying to do:

.h file

#import <UIKit/UIKit.h>


@interface IngredientsRootView : UIViewController <UITableViewDelegate, UITableViewDataSource> {
 UITableView *ingredientsTable;
}

@property (nonatomic, retain) UITableView *ingredientsTable;

@end

.m file I have delegate and data source methods and this code:

ingredientsTable = [[UITableView alloc] initWithFrame:CGRectMake(10, 10, 300, 300) style:UITableViewStylePlain];
 [ingredientsTable setDelegate:self];
 [ingredientsTable setDataSource:self];
 [self.view addSubview:ingredientsTable];

The app doesn't crash, but it doesn't show a table. At the moment I have just set everything definitely as per:

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 10;
}


// the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
 cell.textLabel.text = @"Hello";

    return cell;
}

What am I doing wrong? Thanks

2条回答
祖国的老花朵
2楼-- · 2020-07-23 04:44

Try calling -reloadData on the table view after adding it as a subview.

Also, how is the view set up? Is it created in a XIB or via -loadView?

查看更多
乱世女痞
3楼-- · 2020-07-23 04:46

Did you remembered to add the [window addSubview:[IngredientsRootView view]]; to your app delegate ?

And by the way, instead of inheriting from UIViewController you can just inherit from UITableViewController and you'll get all that functionality for you with no added code.

查看更多
登录 后发表回答