Swift3でuiscrollviewからtouchesmovedを呼ぶ方法

move.gif

何故だかUIScrollViewではtouchesMovedが呼ばれないので困ります。そういう時はUIScrollViewの機能を拡張すれば全く問題ありません。拡張って本当に素晴らしい機能だと思います。

UIScrollViewを拡張する

 
extension UIScrollView {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesBegan(touches, with: event)
        print("touchesBegan")
    }

    override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesMoved(touches, with: event)
        print("touchesMoved")
    }

    override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesEnded(touches, with: event)
        print("touchesEnded")
}
}
 

実装

 
import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var anotherScrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 中身の大きさを設定
        anotherScrollView.contentSize = CGSize(width: 1000, height: 100)
        // スクロールの跳ね返り
        anotherScrollView.bounces = false
        // Delegate を設定
        anotherScrollView.delegate = self

    }

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

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

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


extension UIScrollView {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesBegan(touches, with: event)
        print("touchesBegan")
    }

    override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesMoved(touches, with: event)
        print("touchesMoved")
    }

    override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesEnded(touches, with: event)
        print("touchesEnded")
}
}
 

参考

GitHUb

[swift]touchesMovedが呼ばれない

uiscrollviewからtouchesmovedを呼ぶには? Swift3

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事