我不明白indexOfVC
如何返回索引:ContentViewController
中的dataObject是可选的:
class ContentViewController : UIViewController {
var dataObject:AnyObject?
,当我们调用
indexOfVC
时,pageContent包含html字符串。如果dataObject为空,并且用HTML文本填充pageContent,如何在pageContent中找到dataObject?func viewControllerAtIndex(index:Int)->ContentViewController?{
if (index < 0) || (index >= pageContent.count){
return nil
}
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
var vc = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as ContentViewController
vc.dataObject = pageContent[index]
return vc
}
/* HERE */
func indexOfVC(viewController:ContentViewController) ->Int {
if let dataObject : AnyObject = viewController.dataObject {
return pageContent.indexOfObject(dataObject)
}
else {
return NSNotFound
}
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index : Int = indexOfVC(viewController as ContentViewController)
println("after: index: \(index)") //found 0, then 1, 2,... when scrolling right
if (index == NSNotFound) {
return nil
}
index++
return viewControllerAtIndex(index)
}
//called in viewdidload
func createContentPages(){
var pageStrings = [String]()
for i in 1...11 {
pageStrings.append(String("<html><head></head><body><br><h1>Chapter \(i)</h1><p>This is the page \(i) of content displayed using UIPageViewController in iOS 8.</p></body></html>"))
}
pageContent = pageStrings
}
代码来自:http://www.techotopia.com/index.php/An_Example_Swift_iOS_8_UIPageViewController_Application
最佳答案
答案是dataObject
在调用indexOfVC
时永远不会为零。尽管它是可选的,并且在首次初始化ContentViewController
时将为nil,但是一旦viewControllerAtIndex
方法创建ContentViewController时,它将dataObject
设置为pageContent
数组的元素之一:
var vc = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as ContentViewController
vc.dataObject = pageContent[index]
因此,总体流程为:
起始页面在主视图控制器的
viewDidLoad
中设置:let startingViewController: ContentViewController = viewControllerAtIndex(0)!
这将创建一个VC,并将其
dataObject
设置为pageContent[0]
。如果您随后滑动,则pageViewController将调用
viewControllerAfterViewControler:viewController
。在此调用中,viewController
参数是当前视图控制器。该方法需要知道当前VC的索引,因此它以indexOfVC
作为参数调用viewController
。indexOfVC
读取该视图控制器的dataObject
值,即pageContent[0]
。因此pageContent.indexOfObject(dataObject)
返回整数0。然后将其递增(
index++
),因此对viewControllerAtIndex
的调用将为索引1创建一个新的VC。这将创建一个新的视图控制器,并立即将其dataObject
设置为pageContent [1]。而且周期还在继续...因此,按照当前的编码,
indexOfVC
永远不会传递dataObject
为nil的viewController。但是,如果有的话,它将返回特殊值NSNotFound
。然后viewControllerAfterViewController:
检查返回值,如果它是NSNotFound
,则返回nil
-告诉页面视图控制器不允许滑动。关于ios - uipageviewController:如何在此代码中找到索引?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28716389/