LoginSignup
8
3

More than 5 years have passed since last update.

【 Swift4】高さが可変のUIViewを実装する

Last updated at Posted at 2018-03-17

実行環境

【Xcode】Version 9.2
【Swift】Version 4.0.3

概要

ドラッグ(パン)で高さが変わるUIViewを実装する。

Untitled3.gif

実装

let testView = UIView()

override func viewDidLoad() {
    super.viewDidLoad()

    //対象のUIViewを作成する
    self.testView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height / 2)
    self.testView.backgroundColor = UIColor.green

    //panジェスチャーのインスタンスを作成する
    let gesture = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:)))

    //ジェスチャーを追加する
    self.testView.addGestureRecognizer(gesture)

    //Viewを追加する
    self.view.addSubview(self.testView)
}

@objc func panGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
    //移動量を取得する
    let move = gestureRecognizer.translation(in: self.view)

    //y軸の移動量をviewの高さに加える
    self.testView.frame.size.height += move.y

    //移動量をリセットする
    gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
}

おまけ

UIPanGestureRecognizerstateを使うと、ドラッグ中や指を離した時の処理を分けることができます。
gestureRecognizer.stateは、.began.changed.endedと変化します。

@objc func panGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
    //これを追加する
    switch gestureRecognizer.state {
    case .changed:
        self.testView.backgroundColor = UIColor.blue
    case .ended:
        self.testView.backgroundColor = UIColor.green
    default:
        break
    }   

    //移動量を取得する
    let move = gestureRecognizer.translation(in: self.view)

    //y軸の移動量をviewの高さに加える
    self.testView.frame.size.height += move.y

    //移動量をリセットする
    gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
}

Untitled3.gif

8
3
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
8
3