LoginSignup
1
1

More than 5 years have passed since last update.

[Swift] 画像上にアイコンを乗せ、移動させる単純な方法

Last updated at Posted at 2018-09-10

画像上に乗せたアイコンか人物を移動させて、動かしたい時に、一番単純な方法で実装してみる。

スクリーンショット 2018-09-10 15.36.34.png

StortBoard側

  1. 背景用のImageViewを設定
  2. アイコンor人物用のImageViewを設定
  3. 上下左右移動用のUIButtonを設定
  4. 上下左右にタグ付け(1~4)

各ViewをOutletで接続

MapViewController.swift
    @IBOutlet weak var mapView: UIImageView!
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var topButton: UIButton!
    @IBOutlet weak var rightBUutton: UIButton!
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var bottomButton: UIButton!

ViewController側

移動用Functionを定義。
移動は上下左右の4方向なので、enumで定義してしまいます。

MapViewController.swift
    enum Direction: Int {
        case top = 1, right, left, bottom

        func calcMovedRect(from rect: CGRect, distance: CGFloat) -> CGRect {
            var movedRect = CGRect()
            switch self {
            case .top:
                movedRect = CGRect(x: rect.origin.x, y: rect.origin.y - distance, width: rect.width, height: rect.height)
            case .right:
                movedRect = CGRect(x: rect.origin.x + distance, y: rect.origin.y, width: rect.width, height: rect.height)
            case .left:
                movedRect = CGRect(x: rect.origin.x - distance, y: rect.origin.y, width: rect.width, height: rect.height)
            case .bottom:
                movedRect = CGRect(x: rect.origin.x, y: rect.origin.y + distance, width: rect.width, height: rect.height)
            }
            return movedRect
        }
    }

後はこのfunctionを、IBAction経由で呼ぶか、addTargetで呼ぶかすれば終了

AddTarget経由

    @objc func moveIcon(_ sender: UIButton) {
        guard let direction = Direction(rawValue: sender.tag) else { return }
        self.iconView.frame = direction.calcMovedRect(from: self.iconView.frame, distance: 15)
    }
1
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
1
1