UITableView as a subview?

拜拜、爱过 提交于 2019-12-09 19:26:01

问题


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


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/3555921/uitableview-as-a-subview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!