Jakub
Jakub

Reputation: 13860

Not refreshing screen in programmatically filled TableView

When I scroll down and up again my text in tableView will disappear.

enter image description here enter image description here

And my code is:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [screenDefBuild.elementsToTableView count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
    }

    ScreenListElements *currentScreenElement = [screenDefBuild.elementsToTableView objectAtIndex:indexPath.row];
    cell.textLabel.text = currentScreenElement.objectName;

    currentRow++;    
    return cell;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [tableView setDataSource:self];
    [self.view addSubview:tableView];
}

I also want to fill my table view to entire screen. (grey strap on the top).

Upvotes: 0

Views: 163

Answers (2)

Michał Zygar
Michał Zygar

Reputation: 4092

Answer for the second part of the question- grey strap. You are adding the table view to current view, so you should use the size property of self.view.frame but not the origin. You want this to be set to 0,0.

Change

tableView = [[UITableView alloc] initWithFrame:self.view.bounds];

to

CGRect viewFrame=self.view.frame;
viewFrame.origin=CGPointZero;
tableView = [[UITableView alloc] initWithFrame:viewFrame]; 

As for the first part of your question- it's strange, as you seem to do everything properly. One thing i may suggest is to add [tableView reloadData]; in the end of viewDidLoad.

Upvotes: 0

jackslash
jackslash

Reputation: 8570

I don't know what you're doing with this variable

currentRow++;

But whatever you use that for, i'd wager its breaking your code.

the UITableView will call cellForRowAtIndexPath every time a cell is about to appear on screen regardless of whether it has been on screen before or not. When you scroll down and then scroll back up this variable will have increased beyond the bounds of your data, hence you get empty cells.

You need to design this method in such a way that it can create any cell in the table view at any time. You can't rely on the order that the cells will be made and with scrolling you will have to make the same cell over and over again. Only use indexPath to figure out which cell you are currently supposed to be making.

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html

Upvotes: 2

Related Questions