私は今このコードを使用させてもらっていて、わからないことがあったので
質問させていただきます。
以下私が使っているコードです!
ボタンをタップしたらUIViewを出して
ボタンをスワイプしたらそのボタンが指に沿って移動する・・・
要件を満たしているか分かりませんが、ここからアレンジすればやりたい事ができるようになると思います。
下記のコードをViewControllerにそのまま貼り付けると動くと思います。
ボタンを押すと左に赤いViewがaddされます、そしてUIButtonはドラッグで移動できます。
import UIKit
class ViewController: UIViewController {
var viewCount: CGFloat = 0
let button = CustomButton(type: .Custom)
override func viewDidLoad() { super.viewDidLoad() // ボタンを生成 button.frame = CGRectMake(100, 100, 200, 50) button.setTitle("Button", forState: .Normal) button.setTitleColor(UIColor.blueColor(), forState: .Normal) button.backgroundColor = UIColor.yellowColor() button.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside) button.userInteractionEnabled = true button.tag = 999 button.vc = self view.addSubview(button) } func buttonPressed(sender: UIButton) { if !button.isMoveing { // 赤いViewを画面に追加 let v = UIView(frame: CGRectMake(10, 10 + viewCount * 40 , 30, 30)) v.backgroundColor = UIColor.redColor() view.addSubview(v) viewCount += 1 } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { // タッチイベントを取得 let touchEvent = touches.first! let tag = touchEvent.view?.tag if tag == 999 { moveView(touchEvent, vi: button) } } func moveView<T: UIView>(touchEvent: UITouch, vi: T) { // ドラッグ前の座標 let preDx = touchEvent.previousLocationInView(self.view).x let preDy = touchEvent.previousLocationInView(self.view).y // ドラッグ後の座標 let newDx = touchEvent.locationInView(self.view).x let newDy = touchEvent.locationInView(self.view).y // ドラッグしたx座標の移動距離 let dx = newDx - preDx // ドラッグしたy座標の移動距離 let dy = newDy - preDy // 画像のフレーム var viewFrame: CGRect = vi.frame // 移動分を反映させる viewFrame.origin.x += dx viewFrame.origin.y += dy vi.frame = viewFrame }
}
// CustomButton Class
class CustomButton: UIButton {
var vc: UIViewController! var isMoveing: Bool = false override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) isMoveing = true vc.touchesMoved(touches, withEvent: event) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) isMoveing = false vc.touchesEnded(touches, withEvent: event) }
}
このコードを使っていて、touchEndedの時にある座標だったら〜みたいなことをしています。
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
↑これが使えなくて困っています。何かミスをしているのでしょうか?
touchEnded以外のやり方があるのでしょか?
よくわからないです。分かりやすくお願い致します.
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/04/12 07:43