Swift. Как определить по какому View было сделано касание

Имеется определенное количество View. Нужно понять по какому именно view было сделано нажатие. Пытался найти решение, но не нашел.


Ответы (1 шт):

Автор решения: Andrew

Можно например так:

@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!
@IBOutlet weak var thirdView: UIView!   

и отлавливать:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     if let touch = touches.first {
        if touch.view == self.firstView {
            // 1
        } else if touch.view == self.secondView {
            // 2
        } else if touch.view == self.thirdView {
            // 3
        } else {
            return
        }
    }

}

либо так:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: view)
        if firstView.frame.contains(location) {
            // 1
        } else if secondView.frame.contains(location) {
            // 2
        } else if thirdView.frame.contains(location) {
            // 3
        }
    }

}

так же можно прилепить к каждой вьюхе tag и отлавливать по нему. Вот есть подобный вопрос и ответы

→ Ссылка