Swift accessing and updating tableview in container view

北城以北 提交于 2019-12-20 04:15:50

问题


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.


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/31440378/swift-accessing-and-updating-tableview-in-container-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!