iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Mobile Development

ios 的小小實驗室 !系列 第 17

DAY 17 『 Xib 畫面跳轉 - push 、 present 』

push

刻好畫面後,在 ViewController.swift ( MainVC.swift ) 加入「 利用 push 轉畫面 」的程式碼

  • p.s.
    animated:是否需要動畫效果

在專案底下 New Group / New File / 選 Cocoa Touch Class

在 SecondVC.xib 裡新增一個 Lable ,當在 MainVC 按下 Button 後,即可辨別是否跳頁成功;在 SecondVC 按下 Button 後即可跳回 MainVC 。
在 SecondVC.swift 加入跳回 MainVC 的程式碼


present

在 ViewController.swift ( MainVC.swift ) 加入「 利用 present 轉畫面 」的程式碼

在 SecondVC.swift 加入跳回 MainVC 的程式碼

  • p.s.
    animated : 頁面切換時是否有動畫。
    completion : controller 畫面顯示後執行的程式。
    大部份呼叫 present 時 completion 都是傳入 nil,因為主要是為了顯示 controller 畫面,並不須在畫面顯示後做額外動作。

附上完整程式碼

//  MainVC.swift

import UIKit

class MainVC: UIViewController {

    @IBOutlet weak var btn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.hidesBarsOnTap = true
    }
    
// MARK: - push
    @IBAction func btnAct1(_ sender: UIButton) {
        let toSecondVC = SecondVC()
        self.navigationController?.pushViewController(toSecondVC, animated: true)
    }
    
// MARK: - present
    @IBAction func btnAct2(_ sender: UIButton) {
        self.present(SecondVC(), animated: true, completion: nil)
    }
}

//  SecondVC.swift

import UIKit

class SecondVC: UIViewController {

    @IBOutlet weak var btnToMainVC: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()  
    }
    
// MARK: - push
    @IBAction func btnPush(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
// MARK: - present
    @IBAction func btnPresent(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
}

這樣就完成 push 、 present 轉畫面啦!明天會介紹 Protocol And Delegate,敬請期待!


上一篇
DAY 16 『 改用 xib 進行界面創作 』
下一篇
DAY 18 『 畫面間跳頁傳值 - Protocol And Delegate 』
系列文
ios 的小小實驗室 !30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言