iOS中的UIPageViewController

UIPageViewController

UIPageViewController是一個(gè)用來管理內(nèi)容頁之間導(dǎo)航的容器控制器(container view controller)佃牛,其中每個(gè)子頁面由子視圖控制器管理攘蔽。內(nèi)容頁間導(dǎo)航可以由用戶手勢(shì)觸發(fā),也可以由代碼控制贰剥。

UIPageViewController可以實(shí)現(xiàn)圖片輪播效果和翻書效果.

初始化PageViewController

public init(transitionStyle style: UIPageViewController.TransitionStyle,
            navigationOrientation: UIPageViewController.NavigationOrientation,
                          options: [UIPageViewController.OptionsKey : Any]? = nil)

初始化方法提供三個(gè)參數(shù):

  • TransitionStyle

UIPageViewController翻頁的過渡樣式

  public enum TransitionStyle : Int {
        case pageCurl // Navigate between views via a page curl transition. 卷曲樣式類似翻書效果
        case scroll // Navigate between views by scrolling. UIScrollView滾動(dòng)效果
  }
  • NavigationOrientation

UIPageViewController導(dǎo)航方向

 public enum NavigationOrientation : Int {
        case horizontal // 水平導(dǎo)航
        case vertical // 垂直導(dǎo)航
 }
  • UIPageViewController.OptionsKey

這個(gè)參數(shù)是可選的,傳入的是對(duì)UIPageViewController的一些配置

 public struct OptionsKey : Hashable, Equatable, RawRepresentable {

        public init(rawValue: String)
 }

 extension UIPageViewController.OptionsKey {

    public static let spineLocation: UIPageViewController.OptionsKey
    
    // Key for specifying spacing between pages in options dictionary argument to initWithTransitionStyle:navigationOrientation:options:.
    // Value should be a CGFloat wrapped in an NSNumber. Default is '0'.
    // Only valid for use with page view controllers with transition style 'UIPageViewControllerTransitionStyleScroll'.
    @available(iOS 6.0, *)
    public static let interPageSpacing: UIPageViewController.OptionsKey
}
  • spineLocation

這個(gè)key只有在TransitionStyle是翻書效果pageCurl的時(shí)候才有作用, 它定義的是書脊的位置,值對(duì)應(yīng)著SpineLocation枚舉锅减,默認(rèn)值為UIPageViewController.SpineLocation.min

 public enum SpineLocation : Int {
        case none // Returned if 'spineLocation' is queried when 'transitionStyle' is not 'UIPageViewControllerTransitionStylePageCurl'.
        case min // Requires one view controller.
        case mid // Requires two view controllers.
        case max // Requires one view controller.
 }
  • interPageSpacing

這個(gè)key只有在TransitionStyleUIScrollView滾動(dòng)效果scroll的時(shí)候才有作用, 它定義的是兩個(gè)頁面之間的間距(默認(rèn)間距是0)

數(shù)據(jù)源和代理

數(shù)據(jù)源提供了UIPageViewController內(nèi)容

 weak open var dataSource: UIPageViewControllerDataSource? // If nil, user gesture-driven navigation will be disabled.

UIPageViewControllerDataSource協(xié)議

public protocol UIPageViewControllerDataSource : NSObjectProtocol {

    @available(iOS 5.0, *)
    public func pageViewController(_ pageViewController: UIPageViewController,
                                   viewControllerBefore viewController: UIViewController) -> UIViewController?

    @available(iOS 5.0, *)
    public func pageViewController(_ pageViewController: UIPageViewController,
                                   viewControllerAfter viewController: UIViewController) -> UIViewController?

    @available(iOS 6.0, *)
    // The number of items reflected in the page indicator.
    optional public func presentationCount(for pageViewController: UIPageViewController) -> Int 

    @available(iOS 6.0, *)
    // The selected item reflected in the page indicator.
    optional public func presentationIndex(for pageViewController: UIPageViewController) -> Int
}

協(xié)議中包含了四個(gè)方法,其中兩個(gè)為@required,另外兩個(gè)是@optional.

 public func pageViewController(_ pageViewController: UIPageViewController,
                                   viewControllerBefore viewController: UIViewController) -> UIViewController?

該方法是返回前一個(gè)頁面辐董,如果返回為nil,那么UIPageViewController就會(huì)認(rèn)為當(dāng)前頁面是第一個(gè)頁面不可以向前滾動(dòng)或翻頁白对。當(dāng)NavigationOrientationhorizontal時(shí)掠廓,那么該方法獲得當(dāng)前頁面左邊的視圖控制器

public func pageViewController(_ pageViewController: UIPageViewController,
                                   viewControllerAfter viewController: UIViewController) -> UIViewController?

該方法返回后一個(gè)頁面,如果返回為nil甩恼,那么UIPageViewController就會(huì)認(rèn)為當(dāng)前頁面是最后一個(gè)頁面不可以向后滾動(dòng)或翻頁蟀瞧。當(dāng)NavigationOrientationhorizontal時(shí),那么該方法獲得是當(dāng)前頁面右邊的視圖控制器

代理(delegate)自定義UIPageViewController的行為

weak open var delegate: UIPageViewControllerDelegate?

UIPageViewControllerDelegate協(xié)議

public protocol UIPageViewControllerDelegate : NSObjectProtocol {

    @available(iOS 6.0, *)
    optional public func pageViewController(_ pageViewController: UIPageViewController,
                                            willTransitionTo pendingViewControllers: [UIViewController])

    @available(iOS 5.0, *)
    optional public func pageViewController(_ pageViewController: UIPageViewController,
                                            didFinishAnimating finished: Bool,
                                            previousViewControllers: [UIViewController],
                                            transitionCompleted completed: Bool)

    @available(iOS 5.0, *)
    optional public func pageViewController(_ pageViewController: UIPageViewController,
                                            spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation


    @available(iOS 7.0, *)
    optional public func pageViewControllerSupportedInterfaceOrientations(_ pageViewController: UIPageViewController) -> UIInterfaceOrientationMask

    @available(iOS 7.0, *)
    optional public func pageViewControllerPreferredInterfaceOrientationForPresentation(_ pageViewController: UIPageViewController) -> UIInterfaceOrientation
}

協(xié)議中有5各方法

optional public func pageViewController(_ pageViewController: UIPageViewController,
                     willTransitionTo pendingViewControllers: [UIViewController])

該方法是UIPageViewController開始滾動(dòng)或翻頁的時(shí)候觸發(fā)

optional public func pageViewController(_ pageViewController: UIPageViewController,
                                 didFinishAnimating finished: Bool,
                                     previousViewControllers: [UIViewController],
                               transitionCompleted completed: Bool)

該方法是在UIPageViewController結(jié)束滾動(dòng)或翻頁的時(shí)候觸發(fā)

optional public func pageViewController(_ pageViewController: UIPageViewController,
                                 spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation

該方法在TransitionStylepageCurl并且橫豎屏狀態(tài)變化的時(shí)候觸發(fā)条摸,我們可以重新設(shè)置書脊的位置悦污,比如:如果屏幕是豎屏狀態(tài)的時(shí)候我們就設(shè)置書脊位置是min或max, 如果屏幕是橫屏狀態(tài)的時(shí)候我們可以設(shè)置書脊位置是mid

最后兩個(gè)方法設(shè)置了UIPageViewController支持的屏幕類型

重要的方法和屬性

isDoubleSided

屬性默認(rèn)為NO,如果我們當(dāng)前屏幕僅展示一個(gè)頁面那么不用設(shè)置這個(gè)屬性钉蒲,如果設(shè)置了UIPageViewControllerSpineLocationMid這個(gè)選項(xiàng)切端,效果是翻開的書這樣屏幕展示的就是兩個(gè)頁面,這個(gè)屬性就必須設(shè)置為true了.

open var isDoubleSided: Bool // Default is 'NO'.

setViewControllers

open func setViewControllers(_ viewControllers: [UIViewController]?,
                             direction: UIPageViewController.NavigationDirection,
                             animated: Bool,
                             completion: ((Bool) -> Void)? = nil)

這個(gè)方法是設(shè)置UIPageViewController初始顯示的頁面顷啼,如果doubleSided設(shè)為true了,那么viewControllers這個(gè)參數(shù)至少包含兩個(gè)視圖控制器

NavigationDirection

// Only pertains to 'UIPageViewControllerTransitionStylePageCurl'.
public enum NavigationDirection : Int {
     case forward  // 導(dǎo)航到下一個(gè)頁面
     case reverse  // 導(dǎo)航到上一個(gè)頁面
}

使用

簡(jiǎn)單的實(shí)現(xiàn)滑動(dòng)切換視圖踏枣,即輪播圖

class PageViewController: UIViewController {

    // 懶加載創(chuàng)建UIPageViewController
    lazy var pageViewController: UIPageViewController = {
        // 設(shè)置水平滾動(dòng)
        let pageVc = UIPageViewController(transitionStyle: .scroll,
                                          navigationOrientation: .horizontal,
                                          options: nil)
        pageVc.dataSource = self
        pageVc.delegate = self
        return pageVc
    }()
    // 簡(jiǎn)單的3個(gè)UIViewController
    var viewControllers: [UIViewController] {
        return [RedViewController(), YellowViewController(), BlueViewController()]
    }
    var currentIndex: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        addPageViewController()

        // 設(shè)置初始化顯示視圖控制器
        pageViewController.setViewControllers([viewControllers[currentIndex]],
                                              direction: .forward,
                                              animated: true,
                                              completion: nil)
    }

    func addPageViewController() {
        self.addChild(pageViewController)
        pageViewController.view.frame = self.view.frame
        view.addSubview(pageViewController.view)
        pageViewController.didMove(toParent: self)
    }
}

擴(kuò)展PageViewController實(shí)現(xiàn)數(shù)據(jù)源和代理協(xié)議

extension PageViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        // 顯示前一個(gè)頁面,保證數(shù)組不越界
        if currentIndex - 1 >= 0 {
            currentIndex -= 1
            return viewControllers[currentIndex]
        }
        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        // 顯示后一個(gè)視圖頁面
        if currentIndex + 1 < viewControllers.count {
            currentIndex += 1
            return viewControllers[currentIndex]
        }
        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        print("willTransition - 開始滾動(dòng)")
    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        print("didFinishAnimating - 結(jié)束滾動(dòng)")
    }
}

實(shí)現(xiàn)效果如下

2.gif

相關(guān)實(shí)戰(zhàn)

  • Parchment
    68747470733a2f2f73332d75732d776573742d312e616d617a6f6e6177732e636f6d2f70617263686d656e742d73776966742f70617263686d656e742d64656c65676174652e676966.gif

    68747470733a2f2f73332d75732d776573742d312e616d617a6f6e6177732e636f6d2f70617263686d656e742d73776966742f70617263686d656e742d756e73706c6173682e676966.gif

參考

UIPageViewController

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钙蒙,一起剝皮案震驚了整個(gè)濱河市茵瀑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌躬厌,老刑警劉巖马昨,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異扛施,居然都是意外死亡鸿捧,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門疙渣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來匙奴,“玉大人,你說我怎么就攤上這事昌阿〖⒛裕” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵懦冰,是天一觀的道長(zhǎng)灶轰。 經(jīng)常有香客問我,道長(zhǎng)刷钢,這世上最難降的妖魔是什么笋颤? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮内地,結(jié)果婚禮上伴澄,老公的妹妹穿的比我還像新娘。我一直安慰自己阱缓,他們只是感情好非凌,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著荆针,像睡著了一般敞嗡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上航背,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天喉悴,我揣著相機(jī)與錄音,去河邊找鬼玖媚。 笑死箕肃,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的今魔。 我是一名探鬼主播勺像,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼错森!你這毒婦竟也來了咏删?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤问词,失蹤者是張志新(化名)和其女友劉穎督函,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體激挪,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辰狡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了垄分。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宛篇。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖薄湿,靈堂內(nèi)的尸體忽然破棺而出叫倍,到底是詐尸還是另有隱情偷卧,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布吆倦,位于F島的核電站听诸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蚕泽。R本人自食惡果不足惜晌梨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望须妻。 院中可真熱鬧仔蝌,春花似錦、人聲如沸荒吏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽绰更。三九已至豆混,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間动知,已是汗流浹背皿伺。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留盒粮,地道東北人鸵鸥。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像丹皱,于是被迫代替她去往敵國(guó)和親妒穴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容