从我接触触摸屏的位置获取坐标

时间:2014-11-09 14:34:23

标签: swift coordinates touchscreen

我尝试从我触摸屏的位置获取坐标,以便在此时放置特定的UIImage。

我该怎么做?

6 个答案:

答案 0 :(得分:33)

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)
}

答案 1 :(得分:19)

对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)
    }
}

很高兴听到任何更清晰或更优雅的方法来产生相同的结果

答案 2 :(得分:15)

这是在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)

    }
}

答案 3 :(得分:3)

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)
    }
}

source

答案 4 :(得分:0)

最新的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)
  }
}

答案 5 :(得分:0)

对于SwiftUI,我创建了一个名为 for (TObjectIterator<UClass> It; It; ++It) { if (It->IsChildOf(AActor::StaticClass()) || It->IsChildOf(APawn::StaticClass()) || It->IsChildOf(ACharacter::StaticClass())) { actorClasses.Add(*It); } else if (It->IsChildOf(USceneComponent::StaticClass())) { componentClasses.Add(*It); } else if (It->IsChildOf(UUserWidget::StaticClass())) { widgets.Add(*It); } } 的新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())

SwiftUI基本上是通过UIHostingController包装在ViewController中的。至少那是我的想法。

我希望这会有所帮助!

问候krjw