見出し画像

Swiftで行こう!-- Touchで移動!

参考にタッチ操作でラベルの移動をしてみました。

iPadのSwift PlaygroundsでのコードですがmacのXcodeでやってみました。基本的に同じものです。

みそは関数でラベルを定義してviewDidLoad()で2つのラベルを関数で作っています。

   func makeLabel(frame:CGRect, inColor:UIColor,str:String)->UILabel{
       let label = UILabel(frame: frame)
       label.backgroundColor = inColor
       label.text = str
       label.isUserInteractionEnabled = true
       view.addSubview(label)
       return label
   }

引数ではラベルの位置、背景色、文字を入れるようにしています。そして、

label.isUserInteractionEnabled = true

でタッチで操作、移動できるようにします。

あとタッチの操作ができるようになるコードが

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
       let touchevent = touches.first!
       let view = touchevent.view!
       let old = touchevent.previousLocation(in: self.view)
       let new = touchevent.location(in: self.view)
       view.frame.origin.x += (new.x - old.x)
       view.frame.origin.y += (new.y - old.y)
}

となります。

タッチして動かすときは

func touchesMoved

です。ちなみに

いろいろあります。

全コードです。

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
       super.viewDidLoad()
       let _ = makeLabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100), inColor: .red, str: "Red")
       
       let _ = makeLabel(frame: CGRect(x: 50, y: 50, width: 100, height: 100), inColor: .blue,str: "Blue")
   }
   
   func makeLabel(frame:CGRect, inColor:UIColor,str:String)->UILabel{
       let label = UILabel(frame: frame)
       label.backgroundColor = inColor
       label.text = str
       label.isUserInteractionEnabled = true
       view.addSubview(label)
       return label
       
   }
   
   override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
       let touchevent = touches.first!
       let view = touchevent.view!
       let old = touchevent.previousLocation(in: self.view)
       let new = touchevent.location(in: self.view)
       view.frame.origin.x += (new.x - old.x)
       view.frame.origin.y += (new.y - old.y)
}
   }

シュミレーターで実行してみましょう。こんな感じです。

ちなみにfunc touchesBeganのコードです。

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       let touch = touches.first! //このタッチイベントの場合確実に1つ以上タッチ点があるので`!`つけてOKです
       let location = touch.location(in: self.view) //in: には対象となるビューを入れます
       Swift.print(location)
   }
func touchesBegan

でタッチしたときに座標をとる命令です。コンソールでは

(188.0, 217.5)
(173.5, 261.5)

と座標を取ってきていることがわかります。

この記事が気に入ったらサポートをしてみませんか?