我正在创建一个页面视图应用程序。我已经编写了ViewController的代码:
import UIKit
class ViewController: UIViewController {
var pageViewController : UIPageViewController!
var pageTitles : NSArray!
var pageImages : NSArray!
@IBAction func restartAction(sender: AnyObject) {}
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "This Is Page One!", "This Is Page Two!")
self.pageImages = NSArray(objects: "page1", "page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self // <–– Error
let startVC = self.viewControllerAtIndex(0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(index: Int) -> ContentViewController {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
let vc : ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerBeforeViewController viewController: UIViewController) ->UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if index == 0 || index == NSNotFound {
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerAfterViewController viewController: UIViewController) ->UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if index == NSNotFound {
return nil
}
index++
if index == self.pageTitles.count {
return nil
}
return self.viewControllerAtIndex(index)
}
}
但我在这一行self.pageViewController.dataSource = self
收到错误。错误是:
无法分配属性:&#39; self&#39;是不可改变的
我不确定为什么自我是不可改变的以及如何解决它。如果有人可以请求帮助,请提前感谢。
答案 0 :(得分:3)
在swift中你需要拨打self.pageViewController.setDelegate(self)
代表已被声明为方法,而不是某些情况下的属性
答案 1 :(得分:0)
我认为编译器在这里不是很有帮助 - 尝试将控制器声明为以下数据源协议并查看是否修复了这个奇怪的错误
class ViewController: UIViewController, UIPageViewControllerDataSource { etc