我一直试图在我的情节提要中使用UIPageViewController来创建一组滑动图像,但是我一直遇到此错误:
类型'PageViewController'不符合协议'UIPageViewControllerDataSource'
我不明白为什么。
class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
//for scroll view
lazy var subViewControllers:[UIViewController] = {
return[
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Slide_1") as! ViewController_0,
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Slide_2") as! ViewController_1,
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Slide_3") as! ViewController_2
]
}()
//after viewcontroller
func pageViewController(_pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex:Int = subViewControllers.index(of: viewController) ?? 0
if (currentIndex >= subViewControllers.count - 1) {
return nil
}
return subViewControllers[currentIndex + 1]
}
//before viewcontroller
func pageViewController(_pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex:Int = subViewControllers.index(of: viewController) ?? 0
if (currentIndex <= 0) {
return nil
}
return subViewControllers[currentIndex - 1]
}
override func viewDidLoad() {
super.viewDidLoad()
//setting the initial view for the slider
setViewControllers([subViewControllers[0]],direction: .forward, animated: true, completion: nil)
}
//making style a normal slide
required init?(coder: NSCoder) {
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return subViewControllers.count
}
}
答案 0 :(得分:1)
在属于协议的两种方法中,_
和pageViewController
参数之间应该有一个空格(在页面的前/后)。
下划线表示该方法在调用时不需要该参数的标签。
例如:
func setBlob(_ blob: Blob) -> Bool {
}
被称为:
let myBlob = Blob()
setBlob(myBlob)
如果那里没有_
,它将期望setBlob(blob: blob)
。为了代码整洁,可以方便地更改或忽略参数名称。但是由于参数标签和实际参数名称之间没有空格,因此它认为参数名称为_pageViewController
。
错误显示所在的同一行上应该有一个红色图标,您可以单击该图标以自动填写缺少的方法,以便您可以轻松地查看缺失/不正确的内容。您的类必须实现协议所需的所有方法,并遵循相同的方法签名,否则您将收到此错误。