2015-08-21 7 views
1

Я пытаюсь перемещать кнопку с палец демо в быстром.uibutton пропустить расстояние при перемещении с помощью пальца в swift

Так что я пишу класс UIButton, как нижний. Проблема в том, что кнопка будет пропускать небольшое расстояние при перемещении.

Я хочу знать, почему?

Спасибо!

import UIKit 

class MoveAbleButton: UIButton { 
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {} 
    override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {} 
    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {} 

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { 
     let touch = touches.first 

     if let touchTemp = touch { 
      let t = touchTemp as! UITouch 

      let point = t.locationInView(self) 

      let x = self.frame.origin.x + point.x 
      let y = self.frame.origin.y + point.y 
      let w = self.frame.width 
      let h = self.frame.height 

      self.frame = CGRectMake(x, y, w, h) 

//   let x = self.center.x + point.x 
//   let y = self.center.y + point.y 
//    
//   let newCenter = CGPoint(x: x, y: y) 
//    
//   self.center = newCenter 

      println("touchesMoved (\(point.x),\(point.y))") 
     } 
    } 
} 

ответ

0

Перед перемещением необходимо вычислить расстояние между левым верхним краем кнопки и точкой касания. Вот мой код:

class MoveAbleButton: UIButton { 
var distantX:CGFloat! 
var distantY:CGFloat! 
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    distantX = ((touches.first as! UITouch).locationInView(self)).x 
    distantY = ((touches.first as! UITouch).locationInView(self)).y 
} 
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {} 
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {} 

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { 
    let touch = touches.first 

    if let touchTemp = touch { 
     let t = touchTemp as! UITouch 

     let pointInSuperView = t.locationInView(self.superview) 

     let x = pointInSuperView.x - distantX 
     let y = pointInSuperView.y - distantY 
     let w = self.frame.width 
     let h = self.frame.height 

     self.frame = CGRectMake(x, y, w, h) 

     //   let x = self.center.x + point.x 
     //   let y = self.center.y + point.y 
     // 
     //   let newCenter = CGPoint(x: x, y: y) 
     // 
     //   self.center = newCenter 

     //println("touchesMoved (\(point.x),\(point.y))") 
    } 
} 

}

+0

спасибо так much.really работать нормально – aotian16

Смежные вопросы