iOS 7 change UIView to UITableView

2019-08-22 00:03发布

问题:

I'm using Xcode Version 5.0 (5A1413) and targeting iOS7 for iPhone. I have nothing but a UIViewController with a Table View on it. Everything I've found says to just set the table's dataSource and delegate to the ViewController. No matter what I do the app just crashes immediately. The view never loads even though there's no code written manually at all. Is it no longer possible to put a table onto a non TableViewController?

回答1:

You should implement all required methods from UITableViewDataSource for preventing crash:

  @required

  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;


回答2:

I think you did a common mistake from beginners. You deleted the main view in Interface Builder and then added a Table View.

You have to know that the UIViewController class has a UIView property called view. By default this property is set to the view created with the nib (or Storyboard) file.

To say that the Table View is the main viewcontroller's view you have to right click from the file owner to the tableview and select "view".

Another method if your not comfortable yet with this method is to set the tableview in the first view.



回答3:

Here is the answer - How to add static TableView to ViewController Really you need to implement required methods.



回答4:

There is no such restrictions with iOS 7.0. You can still have a UIViewController in-act as a data source and delegate for UITableView. You just need to implement all the mandatory methods set by these protocols. Could you please update your question with your code and the exception causing the crash. Without this information it would be hard to provide a solution.

I am especially interested in seeing your cellForRowAtIndexPath the way you are constructing cells and reusing them.



回答5:

Add the Delegate and Datasource to the interface:

@interface MyViewController : UIViewController 
                              <UITableViewDataSource, UITableViewDelegate>