开发者

Creating a UITableViewController programmatically

This is what I tried. Nothing appears on the screen and none of the UITableView methods that you are supposed to implement are getting called.

-(void)loadView 
{
    UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 
    self.view = view;
    [view release];
}


- (开发者_运维问答void)viewDidLoad 
{
    [super viewDidLoad];
    UITableViewController *TVC = [[[UITableViewController alloc] 
    initWithStyle:UITableViewStylePlain] autorelease];
    CGRect cgRct = CGRectMake(0, 10, 320, 100);
    UIView *newView = [[UIView alloc] initWithFrame:cgRct];
    TVC.view = newView;
    [newView release];
    [self.view addSubview:TVC.view];
}

I've looked for good examples and tutorials on doing this programmatically but there are none.

What I am trying to achieve is a Table that doenst take up my who screen. Maybe 3/4 of my screen would be good.

Many Thanks Code


The problem is that you're creating a UITableViewController, which is a UIViewController, and will expect to be on the nav stack. What you want to do is create a UITableView, which is a UIView. You are also not setting the table's delegate and data source, which you will need to do to get calbacks.

Your viewDidLoad should look something like this

- (void)viewDidLoad 
{
    [super viewDidLoad];
    UITableView *table = [[[UITableView alloc] initWithStyle:UITableViewStylePlain] autorelease];
    table.dataSource = self;
    table.delegate = self;
    table.frame = CGRectMake(0, 10, 320, 100);
    [self.view addSubview:table];
}

(Note that if you're going to need access to the table outside of the callbacks, you should save it in an ivar rather than declaring it locally, and should retain it. Let me know if you need a few more lines of code to show you what I mean)


Make sure you set the delegate of TVC, with

TVC.delegate = self;

That's the reason why none of those methods are getting called. Also, make sure your class implements the UITableViewDelegate protocol by changing your interface declaration to

@interface YourViewController : UIViewController <UITableViewDelegate> {
    //declare variables here
}

Also, equally important, don't set TVC.view, as this already happens when you initialize the view controller. You're just setting it to a blank view, which is why you're not seeing anything.


iOS7 seems to like this way of init'ing the tableview:

//make tableview
UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 81, 200, 200) style:UITableViewStylePlain];
table.dataSource = self;
table.delegate = self;
[self.dataView addSubview:table];

try that out. Hope it helps someone.


UIView *newView = [[UIView alloc] initWithFrame:cgRct];
TVC.view = newView;

I'll give you a hint. Here you are setting the view of the UITableViewController to an EMPTY VIEW...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜