简体   繁体   中英

iPhone - NSMutableArray - UITableViewCell

Hello Folks

I have a table view which I am loading from a JSON output. I have implemented a functionality of checking and unchecking the UITableView cells.

Problem1 - When I scroll to the bottom of the view, all the selected cells on the top become unselected. I don't know why is that happening, if someone could guide me with that :)

Problem2 - I want to grab all the selected cells in the tableview, and put them into a NSMutableArray. I know there are so many ways to do this but could you guys tell me a more efficient way. I spent almost 2 days figuring this out but still no luck!

Thanks and Best Regards

Well this is happing because you probalbly don't yet full grasp how the UITableView works.

It reuses cells, thats why you call the dequeTableCellWithIdentifier: method on the UITableView . This means that it will reuse one of the cells not longer in view.

Don't add a UITableViewCell for every item in your UITableViewDataSource , this could/will use up to much memory and your UITabelView will feel very slow.

Just make sure that the datasource holds all the data you need for the object, not the UITableViewCell . Meaning title, selected states, ...

What you need to do is set the selected state of the cell in UITableViewDataSource item and look for the selected stated in the UITableViewDataSource and not the UITableViewCell .

So in the object the you retrieve from the JSON add a property selected which takes a BOOL.

Then in UITableViewDataSoutrce method cellForRowAtIndexPath do something like:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"SomeCellIdentiefier";

    UITableViewCell *cell = (SongTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        //Load new cell
    }

    YouJSONObject *item = [self.array objectAtIndex:indexPath.row];

    if (item.selecte) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

}

Then your UITableViewDelegate methods didSelectRowAtIndexPath do something like:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
YouJSONObject *item = [self.array objectAtIndex:indexPath.row]; 

    item.selected = !item.selected;
    if (item.selecte) {
       cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
       cell.accessoryType = UITableViewCellAccessoryNone;
    }
}

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