ボタンタップ時にどこをタップしたか知りたかった
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
}
おわりに
駆け出しすぎて実装に不安が残るが、
とりあえずアウトプットすることが大事と信じることにする。