2014-07-03 19 views
5

Tôi đang cố gắng kéo nút từ vị trí này sang vị trí khác bằng cách sử dụng UITouch. Nhưng tôi không thể kéo nó. Tôi đang phải đối mặt với vấn đề trong việc thêm nút mục tiêu ...Nút kéo nhanh từ một vị trí này sang vị trí khác

số- My

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    let btn_swap = UIButton.buttonWithType(UIButtonType.Custom) as UIButton! 
    btn_swap .setTitle("Drag Me", forState: UIControlState.Normal) 
    btn_swap.backgroundColor = UIColor.yellowColor() 

    btn_swap.addTarget(self, action: "wasDragged:", forControlEvents: UIControlEvents.TouchDragInside) 

    btn_swap.frame = CGRectMake((self.view.bounds.size.width - 100)/2.0, 
     (self.view.bounds.size.height - 50)/2.0, 
     100, 50) 

    self.view.addSubview(btn_swap) 
    self.creation_of_btn() 
} 

func wasDragged (buttn : UIButton, event :UIEvent) 
{ 
    var touch : UITouch = event.touchesForView(buttn) . anyObject() as UITouch 
    var previousLocation : CGPoint = touch .previousLocationInView(buttn) 
    var location : CGPoint = touch .locationInView(buttn) 
    var delta_x :CGFloat = location.x - previousLocation.x 
     var delta_y :CGFloat = location.y - previousLocation.y 
    buttn.center = CGPointMake(buttn.center.x + delta_x, 
     buttn.center.y + delta_y); 

} 
+0

nhờ cho mã cho đồng bằng, điều đó thật tuyệt –

Trả lời

10

Bạn cho một selector sai cho nút của bạn wasDragged:. Vì giao diện phương thức hành động của bạn giống như

func wasDragged (buttn : UIButton, event :UIEvent) 
{ 
} 

slector phải là wasDragged: event:.

btn_swap.addTarget(self, action: "wasDragged:event:", forControlEvents: UIControlEvents.TouchDragInside) 
+3

nó đang làm việc bro ... thanks .. Hãy chỉnh sửa và loại bỏ không gian giữa wasDragged: sự kiện: – ChenSmile

+0

hi tôi đã thực hiện nó trong swift3. nhưng làm thế nào tôi phát hiện vị trí kết thúc bởi vì tôi muốn tái thiết lập nút tại vị trí của mình? – seggy

+0

tôi nhận được câu trả lời http://stackoverflow.com/a/35999687/6619234 – seggy

0

Sự kiện TouchDragInside cũng cần đối số sự kiện cần được chuyển làm đối số thứ hai.

Swift 1:

https://stackoverflow.com/a/24547115/5078763

Swift 2:

btn_swap.addTarget(self,action: #selector(wasDragged(_:event:)),forControlEvents: .TouchDragInside) 

func wasDragged(btnVar : UIButton, evtVar :UIEvent) 
{ 
    let touch : UITouch = (evtVar.touchesForView(btnVar)?.first)! as UITouch 
    let previousLocation : CGPoint = touch .previousLocationInView(btnVar) 
    let location : CGPoint = touch .locationInView(btnVar) 
    let delta_x :CGFloat = location.x - previousLocation.x 
    let delta_y :CGFloat = location.y - previousLocation.y 
    btnVar.center = CGPointMake(btnVar.center.x + delta_x, 
           btnVar.center.y + delta_y); 
} 
Các vấn đề liên quan