我需要一个UIPageViewController来显示与数组中可用数据一样多的UIViewControllers。 假设我有一个Int数组,并且对于每个Int我都希望UIViewController在UILabel中显示其中一个。 为此,我在Main Storyboard中创建了UIPageViewController和UIViewController及其UILabel。
这是我为UIPageViewController编写的代码:
import UIKit
import RealmSwift
class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
lazy var subViewControllers: [UIViewController] = {
return [
self.createNewVC(withName: "CounterViewController"),
self.createNewVC(withName: "CounterViewController"),
self.createNewVC(withName: "CounterViewController")
]
}()
var dataArray: [Int] = [30, 134, 345]
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
setViewControllers([subViewControllers[0]], direction: .forward, animated: true, completion: nil)
}
// Creates a new ViewController
func createNewVC(withName name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
}
// Returns the previous ViewController
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex: Int = subViewControllers.index(of: viewController) ?? 0
if (currentIndex <= 0) {
return nil
}
if let previous = subViewControllers[currentIndex - 1] as? CounterViewController {
previous.daysLeftLabel.text = String(dataArray[currentIndex])
return previous
} else {
return nil
}
}
// Returns the next ViewController
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex: Int = subViewControllers.index(of: viewController) ?? 0
if (currentIndex >= subViewControllers.count - 1) {
return nil
}
if let next = subViewControllers[currentIndex + 1] as? CounterViewController {
next.daysLeftLabel.text = "0"
return next
} else {
return nil
}
}
}
这是UIViewController的代码
import UIKit
class CounterViewController: UIViewController {
@IBOutlet weak var daysLeftLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
NB:“ CounterViewController”也是UIViewController StoryBoardID
问题是,当我第一次向右滚动时,应用程序在此行next.daysLeftLabel.text = "0"
崩溃,说它在展开Optional时发现了一个nil值。
我在这里做什么错了?
我也想借此机会提出一些问题。 正如您可能已经猜到的,在这种情况下,我使用的UIPageViewController拥有相同的UIViewControllers,但显示的数据不同,这是实现此目的的最佳方法?我是在正确执行操作,还是有一种更简便,更干净的方法?
答案 0 :(得分:0)
此行崩溃
next.daysLeftLabel.text = "0"
因为daysLeftLabel
为零,直到VC加载,您需要
class CounterViewController: UIViewController {
@IBOutlet weak var daysLeftLabel: UILabel!
var sendedText = ""
override func viewDidLoad() {
super.viewDidLoad()
daysLeftLabel.text = sendedText
// Do any additional setup after loading the view.
}
}
然后使用
next.sendedText = "0"