Подтвердить что ты не робот

Получение координат из местоположения касаюсь сенсорного экрана

Я пытаюсь получить координаты из того места, где я попал на сенсорный экран, чтобы на данный момент установить определенный UIImage.

Как я могу это сделать?

4b9b3361

Ответ 1

В подклассе UIResponder, таком как UIView:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject()! as UITouch
    let location = touch.locationInView(self)
}

Это вернет CGPoint в координатах вида.

Обновлен синтаксис Swift 3

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.first!
    let location = touch.location(in: self)
}

Обновлен синтаксис Swift 4

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self.view)
}

Ответ 2

Принимая это для Swift 3 - я использую:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: self)
        print(position.x)
        print(position.y)
    }
}

Счастлив услышать более четкие или более элегантные способы получения того же результата

Ответ 3

Это работа в Swift 2.0

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let position :CGPoint = touch.locationInView(view)
        print(position.x)
        print(position.y)

    }
}

Ответ 4

Swift 4.0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: view)
        print(position)
    }
}

источник

Ответ 5

Последний swift4.0, для ViewController

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
    let location = touch.location(in: self.view)
    print(location.x)
    print(location.y)
  }
}

Ответ 6

Для SwiftUI я создал новый файл swift под названием HostingController.swift

import Foundation
import UIKit
import SwiftUI

class HostingController: UIHostingController<ContentView> {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.location(in: view)
            print(position)
        }
    }
}

Затем я изменил следующие строки кода в SceneDelegate.swift

window.rootViewController = UIHostingController(rootView: ContentView())

в

window.rootViewController = HostingController(rootView: ContentView())

SwiftUI в основном обернут в ViewController через UIHostingController. По крайней мере, так я думаю.

Надеюсь, это поможет!

Привет krjw