我不明白indexOfVC
如何返回索引:dataObject在ContentViewController
中是可选的:
class ContentViewController : UIViewController {
var dataObject:AnyObject?
,当我们调用indexOfVC
时,pageContent包含html字符串。如果dataObject为空,pageContent是否填充了html文本,那么如何在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
答案 0 :(得分:1)
答案是dataObject
在indexOfVC
被调用时永远不会为零。虽然它是可选的,并且在ContentViewController
首次初始化时将为nil,但只要viewControllerAtIndex
方法创建ContentViewController,它就会将dataObject
设置为pageContent
的其中一个元素{1}}数组:
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。这将创建一个新的视图控制器并立即设置其{{1 to pageContent [1]。循环继续......
因此,当前编码时,dataObject
从不传递了一个view indexOfVC
为零的viewController。但如果它曾经,它将返回特殊值dataObject
。然后NSNotFound
检查返回值,如果 viewControllerAfterViewController:
,则返回NSNotFound
- 告知页面视图控制器不允许滑动。