'unrecognized selector sent to instance' 将 UITableView 添加到 UIPageViewController 时

'unrecognized selector sent to instance' when adding UITableView to UIPageViewController

我正在尝试创建一个内部有多个水平分页 UITableView 的 PageViewController。 UITableViews 存储在一个数组中;我使用 UIPageViewController setViewControllers 方法将数组中的第一个对象添加到 PageVC:

 [self.pageViewController setViewControllers:[self.tableViews objectAtIndex:0] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

然后我使用 viewControllerBeforeViewControllerviewControllerAfterViewController 方法将剩余的 UITableView 添加到 PageViewController。

但是 setViewControllers 方法产生了以下错误:

 -[UITableView count]: unrecognized selector sent to instance 0x7c347e00
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableView count]: unrecognized selector sent to instance 0x7c347e00'

为什么会出现这个错误?

两个问题。

您需要将视图控制器而不是视图传递给页面视图控制器。对于每个 UITableView,您需要一个 UITableViewController。

如果您将变量 self.tableViews 更改为 self.tableViewControllers(使用您为每个 UITableView 创建的 UITableViewController),您就成功了一半。

另一个问题是 setViewControllers 的第一个参数应该是一个 NSArray。 (NSArray 有一个名为 count 的选择器。)

更改代码以在添加时将第一个 table 视图包装在数组中:

[self.pageViewController setViewControllers:@[ [self.tableViewControllers objectAtIndex:0] ] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]

你应该先看看你正在使用的方法here:

- (void)setViewControllers:(NSArray<UIViewController *> *)viewControllers 
                 direction:(UIPageViewControllerNavigationDirection)direction 
                  animated:(BOOL)animated 
                completion:(void (^)(BOOL finished))completion;

它说参数应该是viewControllers

Parameters:

viewControllers The view controller or view controllers to be displayed.

因此,您必须参加 UIViewcontrollerUITableViewController