gpt4 book ai didi

objective-c - UITableView 数据源和委托(delegate)不会连接到自定义类

转载 作者:可可西里 更新时间:2023-11-01 03:59:34 24 4
gpt4 key购买 nike

我无法将 Storyboard 中 TableView 的数据源和委托(delegate)导出连接到我的自定义委托(delegate)类。我想将这些表函数委托(delegate)给另一个类。关于委派、导出和 Storyboard中的连接,我从根本上误解了一些东西。

背景

我有一个 UIViewController,它的 View 包含一个 UIPickerView 和一个 UITableView
我已经到了我的 UIViewController 太大的地步,我想将与表相关的功能移到另一个类中。

我创建了以下类来包含那些表格方法,例如 numberOfSectionsInTableView:

@interface ExerciseTableDelegate : NSObject <UITableViewDelegate, UITableViewDataSource> 

@property (strong, nonatomic) ExerciseDataController *dataController;

@end

我想在我的 UIViewController 中引用上面的类

@interface ExerciseViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
{
UIPickerView *exercisePicker;
}

@property (strong, nonatomic) IBOutlet ExerciseTableDelegate *tableDelegate;

@end

我希望在 Storyboard中,当我将我的 TableView 的数据源或委托(delegate)导出之一拖到 UITableViewController 上时,它会让我能够连接到我的委托(delegate)类。它没有。

然后我尝试在 Storyboard 中创建一个对象,为其指定类 ExerciseTableDelegate。然后我可以将 TableView 委托(delegate)拖到该对象,但这与我在 AppDelegate 中设置的对象不同。

我的应用委托(delegate)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
ExerciseViewController *rootViewController = (ExerciseViewController *)[[navigationController viewControllers] objectAtIndex:0];

ExerciseTableDelegate *tableDelegate = [[ExerciseTableDelegate alloc]init];
ExerciseDataController *dataController = [[ExerciseDataController alloc] init];

tableDelegate.dataController = dataController;
rootViewController.tableDelegate = tableDelegate;

// Override point for customization after application launch.
return YES;
}
  • 我是否需要将我的对象设为单例并仍然在代表?
  • 我是否需要在代码中而不是在 Storyboard?
  • 在 Storyboard 中创建对象是错误的想法吗?

我觉得我很接近,但我觉得我做得太多了。

最佳答案

如果您想要访问您在应用程序委托(delegate)中设置的 ExerciseTableDelegate 实例,那么您必须在代码中将它连接到您的 TableView ,因为它无法从 Storyboard - 正如您所发现的,在 Storyboard 中添加一个新对象会创建一个新实例。

幸运的是,这实现起来非常简单。在 TableView Controller 的 viewDidLoad 方法中,添加以下内容:

self.tableView.delegate = self.tableDelegate;
self.tableView.datasource = self.tableDelegate;

这将重新指向数据源并委托(delegate)给您的单独对象。

关于objective-c - UITableView 数据源和委托(delegate)不会连接到自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11170772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com