ホーム

UIScrollViewの中のUIImageをドラッグで動かす

o.gif

UIScrollViewの中にUIImageをアドサブビューした後に、UIImageに対してPanジェスチャーを追加するという方法で実装しています。

実装

import UIKit

var drakeIsTheBestInTheWorld = UIImageView()

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var anotherScrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        anotherScrollView.contentSize = CGSize(width: 1000, height: 100)
        anotherScrollView.bounces = false
        anotherScrollView.delegate = self
    }

    func panGesture(sender:UIPanGestureRecognizer) {

        print("YaSuoo!!")

        let point: CGPoint = sender.translation(in: self.view)
        let movedPoint: CGPoint = CGPoint(x: sender.view!.center.x + point.x, y: sender.view!.center.y + point.y)
        sender.view!.center = movedPoint
        sender.setTranslation(CGPoint.zero, in: self.view)
    }

    override func viewDidAppear(_ animated: Bool) {

        super.viewDidAppear(animated)

        drakeIsTheBestInTheWorld = UIImageView.init(frame: CGRect.init(x: 0, y:15, width: 100, height: 100))
        // タッチ操作を enable
        drakeIsTheBestInTheWorld.isUserInteractionEnabled = true
        drakeIsTheBestInTheWorld.image = UIImage(named: "drake")
        self.anotherScrollView.addSubview(drakeIsTheBestInTheWorld)

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture(sender:)))
        drakeIsTheBestInTheWorld.addGestureRecognizer(panGestureRecognizer)

    }

       override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    /* 以下は UITextFieldDelegate のメソッド */
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // スクロール中の処理
        print("didScroll")
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        // ドラッグ開始時の処理
        print("beginDragging")
    }
}

参考

GitHub

Pocket
LinkedIn にシェア

-ホーム

Copyright© off.tokyo , 2021 All Rights Reserved Powered by AFFINGER5.