SwiftのtouchesBeganメソッドを使えば、ユーザーがタップしたビューを取得できる

Swiftでは、touchesBeganメソッドをオーバライドすることで、ユーザがタップしたビューを取得できます。以下はその例です:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self.view)
let tappedView = self.view.hitTest(location, with: event)
// 对点击的view进行处理
if tappedView == yourView {
// 点击了yourView
} else if tappedView == anotherView {
// 点击了anotherView
}
}
}

まずユーザーがクリックしたlocationを取得し、hitTestを使ってクリックされたviewを取得します。その後、ifでユーザーがクリックしたのがどのviewかを判断して対応の処理を行います。

广告
広告は10秒後に閉じます。
bannerAds
bannerAds