简体   繁体   English

在容器视图中快速访问和更新tableview

[英]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. 我想从主视图控制器更新tableview。 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. 我可以通过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. 使用此功能,您可以通过主视图控制器或当前视图控制器访问数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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