我有一个UIPagevViewController
,用于显示4个ViewControllers
。我希望圆点的背景颜色根据我当前所在的视图的背景颜色而变化。虽然我设法使点和首页都具有相同的背景色,但我却没有做到这一点。换句话说,我想根据显示的视图动态更改点背景
import UIKit
class PageViewController: UIPageViewController,UIPageViewControllerDelegate, UIPageViewControllerDataSource {
//my 4 viewControllers used in the UIPageViewController
fileprivate lazy var pages : [UIViewController] = {
return [
self.getViewController(withIdentifier: "firstViewControllerID"),
self.getViewController(withIdentifier: "secondViewControllerID"),
self.getViewController(withIdentifier: "thirdViewControllerID"),
self.getViewController(withIdentifier: "differentViewController")
]
}()
//function that accesses those view controllers used above from the storyboard
fileprivate func getViewController(withIdentifier identifier: String) -> UIViewController
{
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier)
}
/* needed function for the UIPageViewControllerDelegate, UIPageViewControllerDataSource protocols
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
//Some Code. Unnecessary for the question
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
{
//Some Code. Unnecessary for the question
}
*/
//function where the dots colours are set
private func setupPageControl() {
let appearance = UIPageControl.appearance(whenContainedInInstancesOf: [UIPageViewController.self])
appearance.pageIndicatorTintColor = UIColor.gray
appearance.currentPageIndicatorTintColor = UIColor.red
appearance.backgroundColor = pages[appearance.currentPage].view.backgroundColor
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
setupPageControl()
return pages.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
delegate = self
if let firstVC = pages.first {
setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
setupPageControl()
}
}
}
第一张图片->第一页。第二张图片->第二页。看点背景的颜色
答案 0 :(得分:3)
不幸的是,您不能直接访问UIPageViewController内置的页面控件。因此,您必须使用外观代理来更改其外观(就像您已经做的那样)。但是外观代理只会影响事物的 future 实例;因此,一旦页面控件已经存在,设置外观代理将不会有任何影响(如您所见)。
因此,最简单的解决方案是放弃内置于UIPageViewController中的页面控件,而只需使用自己的UIPageControl,即可直接更改其点。您将需要与页面视图控制器进行协调,但这并不困难。
另一种可能性是尝试直接访问UIPageViewController的UIPageControl。这很脆弱,因为没有官方权限,但是这里已经讨论了该技术,例如this answer。