ホーム

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

-ホーム
-,

Copyright© off , 2020 All Rights Reserved Powered by AFFINGER5.