天天看點

基于Swift的iOS應用程式開發:獲得螢幕點選的坐标

1、我在界面上放置了兩個文本輸入框,用來顯示最終獲得到的坐标:

基于Swift的iOS應用程式開發:獲得螢幕點選的坐标
@IBOutlet weak var textFieldXPoint: UITextField!

@IBOutlet weak var textFieldYPoint: UITextField!
           

2、重載touchedBegan方法:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let firstTouch:UITouch = touches.first!
    let firstPoint = firstTouch.location(in: self.view)
    let x:CGFloat = firstPoint.x
    let y:CGFloat = firstPoint.y
        
    self.textFieldXPoint.text = "\(x)"
    self.textFieldYPoint.text = "\(y)"
}