0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

swift辞書「画面遷移をプログラムで行う」

Last updated at Posted at 2021-02-23

お断り

この記事は自分専用メモなのですごい初歩的な事しか書いていませんがご了承下さい。
確認環境
Interface:Storyboard
Life Cycle:UIKit App Delegate
Language:Swift
◉Use Core Data
__◉Host in CloudKit
◉Include Tests

この記事で出来る様になる事

swiftのコードから画面が切り替えられる様になる。

実装

UIの実装

View Controllerをもう一つ配置して動きが分かりやすい様にbackgorundから好きな色を選びましょう。始めからあったView Controllerから新しく作ったView Controllerに向けてcontrolキーを押しながらドラックをします。そうすると色々な選択肢が出来てくるのでPresent Modallyを選択して下さって下さい。
見た目はこのままでは問題無いのですが、このままでは下にスワイプすると元の画面に戻ってしまうので変更を加えます。先ほど背景の色を変えた方のView ControllerのPresentationをFull Screenに変更して下さいこれで成功している筈です。スクリーンショット 2021-02-23 23.54.57.png最後にエラーを駆逐していきます。エラーをコピーしてdeepl翻訳にぶち込むとビューコントローラを区別する名前が付いていないよ的な事が返ってきたのでビューコントローラに名前を付けてやりましょう。二つの画面を繋ぐ矢印を選択するとIdentifierと言ういかにも名前を付けれそうな場所を発見したのでそこに適当に名前を付けましょう。名前を考えるのはめんどくさいので今回はmoveとでもしましょう。これでエラーも駆逐できたので、ひとまづUIは完成です。

コードの実装

今更気づいたのですが動くきっかけを忘れていました。UIの実装を直すのはめんどくさいので、スマホが振られた時に画面の遷移をする様にしたいと思います。皆さんは好きなどんなトリガーでも大丈夫です。例buttonが押された、画面がスワイプされたなど。では結論のコードを貼ってから解説していきます。

import UIKit
import CoreMotion

class ViewController: UIViewController {
    
    let MotionSensor = CMMotionManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getAccelerometer()
    }
    func getAccelerometer() {
            MotionSensor.accelerometerUpdateInterval = 0.2
            MotionSensor.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: {
                accelerometerData,error in
                let x = accelerometerData!.acceleration.x
                let y = accelerometerData!.acceleration.y
                let z = accelerometerData!.acceleration.z
                let synthetic = (x * x) + (y * y) + (z * z)

                if synthetic >= 6 {
                    self.move()
                }
            })
    }
    func move() {
        performSegue(withIdentifier: "move", sender: nil)
    }
}

実機で試した所無事に緑色になりました。動きの部分は今回の話とは一ミリも関係ないのでよかったら調べて見て下さい。解説の移ります。遷移の処理をしているのはfunc move()関数の中です。でも見れば分かる様にwithIdentifierに先ほど指定したmoveの名前を入れて、よくわからないsenderにはnilを入れとけば動く事が分かりましたね!今回はこれで終わりです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?