简体   繁体   中英

Swift accessing and updating tableview in container view

This is kind of confusing but I will do my best to explain. I have a view controller with a container view. In the container view is a table view. I want to update the tableview from the main view controller. For example, the table view will contain a list of names. As the user types in a name into a text field, the table view will update to find names that match what the user inputed.

The main question is:

How can I update the table view from the main view controller?

Note: I can't use prepare for segue because the data will be changing.

I figured it out...

I can access the view through childviewcontrollers. Here's the code I used:

    let childView = self.childViewControllers.last as! ViewController
    childView.List = self.nameList
    childView.tableView.reloadData()

This is actually a beginner question and I would be happy to help. You need to find a place to store your data and then you can access it based on your need. That's what we normally call model.

You can take advantage of one of the design patter: shared instance. It will be existing during the application life cycle. See the following example.

You can have a model class like this:

// .h
@interface DataManager : NSObject
+ (instancetype)sharedManager;
@property (strong, nonatomic, readonly) NSMutableArray *data;
@end

// .m
@interface DataManager : NSObject
@property (strong, nonatomic, readwrite) NSMutableArray *data;
@end

@implementation DataManager

+ (instancetype) sharedManager {
    static DataManager *sharedInstance = nil;
    static dispatch_once_t dispatchOnce;
    dispatch_once(&dispatchOnce, ^{
        sharedInstance = [[self alloc] init];
        sharedInstance.data = [[NSMutableArray alloc] initWithCapacity:5];
    });
    return sharedInstance;
}
@end

Using this, you can access your data via your main view controller or your presenting view controller.

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