在Swift中,我目前在我的第一个视图控制器中有以下代码,但是当我滑动时没有任何反应?我的代码出了什么问题?我还需要实施别的吗?非常感谢SO用户,感谢它。
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var myViewControllers = Array(count: 4, repeatedValue:UIViewController())
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let pvc = segue.destinationViewController as UIPageViewController
pvc.dataSource = self
let storyboard = UIStoryboard(name: "Main", bundle: nil);
var vc0 = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as UIViewController
var vc1 = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as UIViewController
var vc2 = storyboard.instantiateViewControllerWithIdentifier("ThirdViewController") as UIViewController
var vc3 = storyboard.instantiateViewControllerWithIdentifier("FourthViewController") as UIViewController
self.myViewControllers = [vc0, vc1, vc2, vc3]
pvc.setViewControllers([myViewControllers[1]], direction:.Forward, animated:false, completion:nil)
println("Loaded")
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var currentIndex = find(self.myViewControllers, viewController)!+1
if currentIndex >= self.myViewControllers.count {
return nil
}
return self.myViewControllers[currentIndex]
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var currentIndex = find(self.myViewControllers, viewController)!-1
if currentIndex < 0 {
return nil
}
return self.myViewControllers[currentIndex]
}
}
答案 0 :(得分:1)
抱歉,您的代码对我来说非常合适。我做了一个简单的测试(之前从未使用过UIPageViewController),只需一个按钮就可以从初始VC转到页面VC,故事板中的两个已断开连接的VC将以编程方式编写(我直接从上面粘贴)和给了页面VC。 3个可见页面中的每一个都用标签标识。而且它们都很好。
您的UIPageViewController是否已实例化?您上面的两个委托例程是否被调用?
我怀疑您没有正确设置故事板。这是我的:
当iOS运行您的应用程序时,它会将控制权转移到初始VC。这是您编写代码的代码,在上面的源代码中称为ViewController
。那不是UIPageViewController
;它是一个普通的UIViewController
,它在这里说:
class ViewController: UIViewController, UIPageViewControllerDataSource {
UIPageViewControllerDataSource
位只是说它还提供告诉UIPageViewController
要显示的内容的例程。当您从ViewController
中执行segue时,prepareForSegue
代码会运行,并将segue的目标(预期为UIPageViewController
)与其他4个VC编程。为了使segue工作,我将UIButton
拖到故事板中的第一个ViewController
,并将UIPageViewController
拖到右侧。然后从按钮控制拖动到UIPageViewController。你应该得到一个弹出窗口,询问你想要什么样的segue。我选择了模态。当您运行该应用程序时,您应该看到该按钮。当您按下按钮时,您应该看到VC1,向左或向右滑动将显示其他。