ボタンをタップした時のタップ位置の座標を取得したい
開発環境 Xcode9.4 / Swift4.1
ボタンをタップした時に、ボタン内のどの部分をタップしているのかを知るために座標の取得を行いたいです。調べたところ、タップ座標の取得にはtouchesBeganメソッドを用いるとわかったので、以下のようなプログラムを作成しました。(関係無いと思われるコードは省略しました。)
Swift
1import UIKit 2import CoreMotion 3import GameplayKit 4 5class TaskViewController: UIViewController{ 6 7 fileprivate var myButton:UIButton! 8 fileprivate var smallView:UIView! 9 10 //中略 11 12 override func viewDidLoad() { 13 14 //中略 15 16 myButton = UIButton() 17 myButton.frame=CGRect(x: 0, y: 0, width: 90, height: 90) 18 myButton.layer.masksToBounds = true 19 myButton.setBackgroundImage(self.createImageFromUIColor(UIColor.red), for: UIControlState()) 20 myButton.setBackgroundImage(self.createImageFromUIColor(UIColor.red), for: .highlighted) 21 myButton.setBackgroundImage(self.createImageFromUIColor(UIColor.lightGray), for: .disabled) 22 myButton.layer.cornerRadius = 45.0 //赤色ボタンを円形にする 23 myButton.layer.position = shuffleArray[0] //初期位置 24 myButton.showsTouchWhenHighlighted = true 25 26 // 背景の指定 27 // 4.7inchの画面サイズは375×667 28 smallView = UIView() 29 smallView.frame = CGRect(x: 0,y:0,width:375,height:667) 30 smallView.backgroundColor = UIColor.white 31 32 // myButtonをタップした時にonMyButtonイベントが発生 33 myButton.addTarget(self, action:#selector(TaskViewController.onMyButton(_:)), for: .touchUpInside) 34 self.view.addSubview(self.smallView); 35 self.view.addSubview(self.myButton); 36 } 37 38 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 39 for touch: AnyObject in touches { 40 // 座標取得 41 let point = touch.location(in: self.view) 42 print(point) 43 } 44 } 45 46 // タップ回数をカウント 47 @IBAction func onMyButton(_ sender: UIButton){ 48 myButton.isEnabled = false 49 counter+=1 50 51 // タップ時刻を測定 52 let formatter = DateFormatter() 53 formatter.timeZone = TimeZone.ReferenceType.local 54 formatter.dateFormat = "HH:mm:ss.SSS" // *時*分**.***秒 55 let date2=Date() 56 let dateStr2 = formatter.string(from: date2) 57 58 print(dateStr2,counter,"回目") 59 60 // タップ時刻と回数を配列に格納 61 csvData.append([String(dateStr2),String(counter),"回目"]) 62 63 if counter>=28 { 64 changeView() 65 } 66 67 //0.5秒間隔でタップボタンを表示 68 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { 69 self.doComputer3() 70 } 71 72 } 73 74 //中略 75 76}
しかし、実行したところ、ボタンをタップした時の座標は取得できませんでした。ボタンタップ時にtouchesBeganメソッドが作動していないことが原因と考え、onMyButtonの中にコードを入れればいいのではないかと思い、そのまま中に貼り付けても見たのですが上手くいきませんでした。具体的にどのような方法を取ればいいのかわからない状態です。ご教示いただけますでしょうか。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/10 01:59
2018/07/11 07:12
2018/07/11 08:16
2018/07/11 09:00