0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ボタンタップ時の領域内タップ位置判定の愚考

Last updated at Posted at 2020-02-06

ボタンタップ時にどこをタップしたか知りたかった

iOSアプリ開発の駆け出しエンジニアが、
ボタンタップイベント発生時に、ボタン内のどこをタップしたかを取得する実装を愚考した。
今回は、ボタン内を三分割した場合の位置をenumで持つことにした。

実際に作成したenum

縦横方向それぞれのenumを持つenumを定義し、
initで位置を判定、失敗時はnone

/// ボタン内のタップ位置取得
public enum ButtonPointer {
    /// 縦方向
    enum Vertical {
        case none
        case top
        case middle
        case bottom
        
        init(of button: UIButton, for event: UIEvent) {
            if let location = event.touches(for: button)?.first?.location(in: button){
                if location.y < button.frame.size.height / 3 {
                    self = .top
                } else if location.y < button.frame.size.height / 3 * 2 {
                    self = .middle
                } else {
                    self = .bottom
                }
            } else {
                self = .none
            }
        }
    }
    
    /// 横方向
    enum Horizontal {
        case none
        case left
        case center
        case right
        
        init(of button: UIButton, for event: UIEvent) {
            if let location = event.touches(for: button)?.first?.location(in: button){
                if location.x < button.frame.size.width / 3 {
                    self = .left
                } else if location.x < button.frame.size.width / 3 * 2 {
                    self = .center
                } else {
                    self = .right
                }
            } else {
                self = .none
            }
        }
    }
}

usage

// addTargetでボタンにイベントを追加した場合
@objc func didTapButton(_ sender: UIButton, event: UIEvent) {
    print(ButtonPointer.Vertical(of: sender, for: event))
    // → top
}

// ボタンのイベントをIBActionで紐づけた場合
@IBAction func didTapButton(_ sender: Any, forEvent event: UIEvent) {
    guard let sender = sender as? UIButton else { return }
    print(ButtonPointer.Vertical(of: sender, for: event))
    // → left
}

おわりに

駆け出しすぎて実装に不安が残るが、
とりあえずアウトプットすることが大事と信じることにする。

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?