【问题标题】:Reload TableView from different ViewController using Objective-C使用 Objective-C 从不同的 ViewController 重新加载 TableView
【发布时间】:2016-11-23 15:17:14
【问题描述】:

我不确定如何实现这一点,因此我在问这个问题。

我有 2 个名为 abVCxyVC 的 ViewController(VC)。 abVC 仅包含 TableViewxyVC 仅包含一个按钮。

当我点击xyVC 上的按钮时,它应该在abVC 内重新加载tableview,而不是移动到abVC

有可能吗?如果是..那么请帮助我,怎么做?

【问题讨论】:

  • 你可以使用 NSNotifications
  • 在 abVC 中添加 NSNotidfication Observer。按下按钮时从 xyVC 发布通知。
  • 另一种方法是使用委托。但这取决于应用的架构。

标签: ios objective-c uitableview reload


【解决方案1】:
  1. 在您的按钮操作方法中添加这一行

    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadTable" object:nil];

  2. 在你已经实现表格的地方添加这段代码,所以在abVC

    1. viewDidLoad:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableViewData) name:@"ReloadTable" object:nil];

    1. 添加以下方法

    - (void)reloadTableViewData{
    [self.myTableView reloadData];
    }

    1. 实现dealloc 方法(防止崩溃)

    - (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ReloadTable" object:nil];
    }

【讨论】:

    【解决方案2】:

    你可以同时使用 block 和 NSNotification。

    使用 block 可以如下实现:

    在 xyzVC.h 中创建如下属性:

    @property(strong,nonatomic)void(^callBack)();
    

    在 xyzVC.m 中综合该属性

    @synthesize callBack
    

    在按钮点击事件中调用这个块

    - (IBAction)btnClick:(UIButton *)sender {
    
    if (callBack)
        {
            callBack();
        }
    
    }
    

    在你想要回调的地方实现它:

    [abVC setCallBack:^{
            //reload your tableview here
        }];
    

    使用 NSNotification 可以如下实现:

    在 abcVC.m 中注册接收通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableView) name:@"ReloadTable" object:nil];
    
    - (void)reloadTableView{
      // Reload your tableview here
    }
    

    现在发布来自 xyzVC 的通知

    - (IBAction)btnClick:(UIButton *)sender {
    
      [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadTable" object:nil];
    
    }
    

    注意:如果您使用的是 NSNotification,请不要忘记在关闭视图控制器时将其删除

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-14
      • 2015-08-12
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2020-03-25
      • 2021-05-28
      • 2019-07-16
      相关资源
      最近更新 更多