简体   繁体   中英

UITableView doesn't appear correctly - why?

I use Xcode 5 and storyboard where I use navigation controller and table view, and in the following code called RootViewController.h ,

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController
@property NSMutableArray *objects;
@end

and RootViewController.m ,

#import "RootViewController.h"

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_objects addObjectsFromArray:@[@"Apple",@"Google",@"Intel"]];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"%d", _objects.count);
    return _objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = @"A";

    return cell;
}

@end

Xcode says "Build Succeeded" but the resultant screen doesn't have the rows rendered correctly.
It returns empty rows and title called Root View Controller .

Why?
I think I correctly write the three required method in numberOfRowsInSection , cellForRowAtIndexPath , and numberOfSectionInTableView , and I don't think I need to define protocol in header file since it's already defined in the parent UITableViewController .

And for some reasons the debug NSLog function in the numberOfRowsInSection method isn't executed.

So what am I missing here? And how can I fix it?

Thanks.

The problem is that _objects is nil - when you try to add objects to nothing the result is nothing.

So you need to create the array instead of adding to it. Change this line

[_objects addObjectsFromArray:@[@"Apple",@"Google",@"Intel"]];

to this

_objects = [NSMutableArray arrayWithObjects:@"Apple", @"Google", @"Intel", nil];

In your storyboard, you also need to set the cell identifier of the UITableViewCell (tutorials galore on how to do this).

Put inside viewDidLoad

self.title = @"some title";

To change the title of NavigationBar

You need to create objects before you can add anything to it:

- (void)viewDidLoad
{
    [super viewDidLoad];
    _objects = [NSMutableArray new];
    [_objects addObjectsFromArray:@[@"Apple",@"Google",@"Intel"]];
}

Did you set the tableview delegate? Did you set the tableviewcell correctly in storyboard?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM