ios導航欄-UINavigationController使用與分析

UINavigationController就一本書一樣,而UIViewController就是它的每一頁,我們可以一頁一頁的翻,也可以瞬間跳到某一頁,或者回歸的過去的某一頁。

構成

我們首先要有一個rootViewController,裝進UINavigationController。

例如在AppDelegate的didFinishLaunchingWithOptions中

let navVC = UINavigationController(rootViewController: ViewController())
window?.rootViewController = navVC
window?.backgroundColor = UIColor.gray
window?.makeKeyAndVisible()

ViewController()創建一個UIViewController來初始化UINavigationController, 這樣ViewController()作為導航欄的第一頁顯示出來。

UINavigationController的組成, 引用一下官網的

UI元素除了UIViewController的數組外,還有navigationBar,toolbar。

接下里我們豐富一下,將其UI元素全部用上。

ViewController的viewDidLoad中加入代碼

// 顯示toolbar
self.navigationController?.isToolbarHidden = false
self.setToolbarItems([UIBarButtonItem(barButtonSystemItem: .camera, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .bookmarks, target: nil, action: nil)], animated: false)
    
// 設置navigationBar的title
self.title = "root view"
    
// 設置navigationBar按鈕
self.navigationItem.setLeftBarButton(UIBarButtonItem(barButtonSystemItem: .add, target: nil, action: nil), animated: false)
self.navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil), animated: false)

注意:toolbar的items的設置,是與UIViewController關聯的,不要UINavigationController上setItems是不會顯示的

跳轉

Push

push就是將VC一個一個疊上去,默認行為是從右側進入

self.navigationItem.setRightBarButton(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.pushAction(sender:))), animated: false)

func pushAction(sender:UIBarButtonItem) {
    self.navigationController?.pushViewController(ViewController2(), animated: true)
}    

我們將done按鈕加入push動作, 點擊done,從右到左進入,這時候系統會添加一個navigationBar item,用于pop到下層頁面,title就是下層頁面設置的title

push對應的返回接口是pop

self.navigationController?.popViewController(animated: true)

Present

說道跳轉,這里也提一下presentpresent跳到另外一個頁面,默認行為是從下而上,除了表現上與push不一樣

  • 不是UINavigationController的管理范疇,UIViewController可直接present到其他頁面
  • 同一個UIViewController不可以present兩次,但present起來的vc是可以再次present
  • present類似模態窗口,在這個窗口dissmiss前,交互只能在這個窗口做,之前的頁面不可交互和變化, 就仿佛你放下一本書,就拿起另外一本書,不能同時看兩本書

present對應的消失接口是dissmiss

self.dismiss(animated: true, completion: nil)

Show

8.0以后提供了show方法,這個是根據viewController所處容器,使用容器的跳轉行為,例如viewController所處容器為navigationController(viewController的容器還有splitViewController),就和push一樣

open func show(_ vc: UIViewController, sender: Any?)

自定義跳轉方式(轉場動畫)

自定義轉場動畫,需要制定兩個因素

  • 從哪個viewController跳轉到哪個viewController
  • 動畫內容

自定義 Present

我們嘗試改寫present的動畫效果,它默認是由下而上,改成自上而下

func pushAction(sender:UIBarButtonItem) {
    let vc = ViewController2()
    vc.transitioningDelegate = self // 實現UIViewControllerTransitioningDelegate協議
    self.present(vc, animated: true, completion: nil)
}

實現UIViewControllerTransitioningDelegate協議, 下面就是用來實現,present和dismiss動畫的

@available(iOS 2.0, *)
optional public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?

    
@available(iOS 2.0, *)
optional public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?

這兩個接口需要返回id<UIViewControllerAnimatedTransitioning>

UIViewControllerAnimatedTransitioning

// 轉場時間
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
// 動畫
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning)

接下來需要創建一個id<UIViewControllerAnimatedTransitioning>的類,

class PresentAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
        let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
        let containerView = transitionContext.containerView
        
        // 將跳轉后的頁面,設置到屏幕上方
        toViewController?.view.frame = (fromViewController?.view.frame)!
        toViewController?.view.frame.origin.y -= (toViewController?.view.frame.height)!
        
        // 添加到轉場動畫容器上,
        containerView.addSubview((toViewController?.view)!)
        
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
            // 回歸的屏幕位置
            toViewController?.view.frame = (fromViewController?.view.frame)!
        }, completion: { (complete:Bool) -> Void in
            transitionContext.completeTransition(true)
        })
    }
}

經過我打印地址研究,得出以下結論

  • containerView是做動畫用的容器, 初始狀態是將跳轉前頁面(較為頂層的一個view,如果vc在navigationController中就是naviController的view)添加為自己的subview
  • fromViewController不是跳轉前vc, 只是將跳轉前頁面添加為自己的subview,用來做舊頁面的退出動畫
  • toViewController則是跳轉后vc,做新頁面的登臺動畫
  • transitionDuration時間是提供給系統的,提供跳轉時系統的默認表現,自定義animate的時間最好和其保持一致
  • containerView臨時產生,在動畫結束后,從UI上撤掉,但view的改變會遺留下來

注意:transitionContext.completeTransition(true)是必須要調用的,否則系統認為轉場為完成,第二頁不能進行任何交互

自定義 Dismiss

dismiss 與 present 類似,只是fromViewController變成了第二頁,toViewController變成了第一頁, 記住上述的那幾條結論來理解containerView.addSubview

class DismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 2
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
        let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
        let containerView = transitionContext.containerView
        containerView.addSubview((toViewController?.view)!)
        containerView.addSubview((fromViewController?.view)!)
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
            fromViewController?.view.alpha = 0.0
        }, completion: { (complete:Bool) -> Void in
            transitionContext.completeTransition(true)
        })
    }
}

自定義 Push

只是掛接delegate的位置不同

// 自定義navigationController動畫
self.navigationController?.delegate = self

實現同樣和上面一樣,返回id<UIViewControllerAnimatedTransitioning>, 為了簡單,我們做之前presentdismiss一樣的動畫

func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    if operation == .push {
        return PresentAnimator();
    } else {
        return DismissAnimator();
    }
}

交互式動畫

最后在說一個present的交互動畫

交互式動畫就隨手勢做的動畫,手拖的距離,來決定動畫執行的進度

需要再實現UIViewControllerTransitioningDelegate協議中的交互式接口,要求返回一個id<UIViewControllerInteractiveTransitioning>

optional public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?

    
optional public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?

這個交互式動畫,依賴于之前設置的動畫方式,只是用來設置百分比,這個百分比需要你自己不斷提供給他,一般用手勢來不斷調用id<UIViewControllerInteractiveTransitioning>的update接口,我們為了簡單,用timer來模擬

創建一個id<UIViewControllerInteractiveTransitioning>

class InteractiveAnimator: UIPercentDrivenInteractiveTransition {
    
}

viewController中加入屬性

var interactiveAnimator:InteractiveAnimator = InteractiveAnimator()
var timer:Timer? = nil
var times:CGFloat = 0;

修改接口

func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?
{
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timeUpdate), userInfo: nil, repeats: true);
    return interactiveAnimator
}
    
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?
{
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timeUpdate), userInfo: nil, repeats: true);
    return interactiveAnimator
}

func timeUpdate() {
    times += 1
    if times <= 5 {
        let per:CGFloat = times/5
        interactiveAnimator.update(per)
    } else {
        timer?.invalidate()
        interactiveAnimator.finish()
    }
}

timeUpdate的會該5次百分比,這個動畫也分5下完成, 每秒變化一次。timeUpdate這是里timer來調用的,你可以用任意的交互方式來調用,百分比自己來計算

demo 地址 記得 pod install

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,443評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,530評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,407評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,981評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,759評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,204評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,263評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,415評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,955評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,650評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,892評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,675評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,967評論 2 374

推薦閱讀更多精彩內容