iOS 如何从另一个类访问 [tableView reloadData] [英] iOS how to acces [tableView reloadData] from another class

查看:21
本文介绍了iOS 如何从另一个类访问 [tableView reloadData]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 viewController,它有一个属性:UIScrollView,并且同一个控制器包含一个 tableView.我的 UIScrollView 包含按钮.我如何使用 [tableView reloadData] 触摸其中的一些按钮?tableView 数据源和委托位于 viewController 上.

I have an viewController, which has a property:UIScrollView, and same controller contains a tableView. My UIScrollView contains buttons. How can i use [tableView reloadData] from touching some of this buttons? tableView data source and delegate is on viewController.

MyViewController:

@property (strong, nonatomic) MyScrollView* scrollView; 
@property (strong, nonatomic) IBOutlet UITableView *table; 

MyScrollView 类:

没有属性和 5 个以编程方式创建的按钮.

no property and 5 buttons created programatically.

推荐答案

在更好地理解您要做什么之后,我想我会使用委托.尽管还有其他方法可以做到这一点,但我认为委托是灵活的,如果您还没有使用它们,那么现在是了解它们的好时机.

After better understanding what you're trying to do I think I would use delegates. Although there are other ways to do this I think that delegates are flexible and if you haven't used them yet then this is a good time to learn about them.

如果一个类希望采用我们的协议,我们定义了它需要实现的委托方法:MyScrollView.h

We define the delegate methods that a class needs to implement if it wishes to adopt our protocol: MyScrollView.h

@protocol MyScrollViewDelegate <NSObject>
-(void)reloadTableData;
@end

@interface MyScrollView : UIScrollView
@property (nonatomic,weak) id<MyScrollViewDelegate> delegate;
@end

然后在实现中我们执行以下操作:

Then in the implementation we do the following:

MyScrollView.m

// Set the button's target
[button addTarget:self action:@selector(reloadData) forControlEvents:UIControlEventTouchUpInside];

// Here we check if our delegate responds to the reloadTableData selector and if so we call it
-(void)reloadData
{
    if ([self.delegate respondsToSelector:@selector(reloadTableData)])
    {
        [self.delegate reloadTableData];
    }
}

在 MyViewController 的实现中,我们添加了 MyScrollViewDelegate 并实现了 reloadTableData 方法:

In the implementation of MyViewController we add the MyScrollViewDelegate and implement the reloadTableData method:

MyViewController.m

@interface MyViewController () <MyScrollViewDelegate>
@property (strong, nonatomic) MyScrollView* scrollView; 
@property (strong, nonatomic) IBOutlet UITableView *table; 
@end

// Set the delegate after you've created scrollView
self.scrollView.delegate = self;

// Once the delegate is called we simply reload the table data
-(void)reloadTableData
{
    [self.table reloadData]
}

这篇关于iOS 如何从另一个类访问 [tableView reloadData]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆