2015-08-15 53 views
0

我需要創建一個可拖動的UITextView。 我設法創建一個可拖動的視圖,我試圖添加一個TextView作爲子視圖,但它不起作用,TextView不可編輯,它沒有出現在視圖內部,但在它下面。Draggable UITextView

這是我創建的自定義視圖代碼:

class DraggableView: UIView { 

var lastLocation:CGPoint = CGPointMake(0, 0) 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    // Initialization code 
    var panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:") 
    self.gestureRecognizers = [panRecognizer] 

    self.backgroundColor = UIColor.redColor() 

    //add UITextView 
    var text = UITextView() 
    text.backgroundColor = UIColor.brownColor() 
    text.text = "This is a test" 
    text.frame = CGRectMake(self.center.x, self.center.y, 40, 40) 
    self.addSubview(text) 
} 

required init(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

func detectPan(recognizer:UIPanGestureRecognizer) { 
    var translation = recognizer.translationInView(self.superview!) 
    self.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y) 
} 

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    // Promote the touched view 
    //self.superview?.bringSubviewToFront(self) 

    // Remember original location 
    lastLocation = self.center 
} 
}  

我該如何正確一個TextView添加到一個拖動看法?

回答

0

試試這個代碼,我更新了detectPan方法,可以ü需要調整按您的要求

class DraggableView: UIView { 

var lastLocation:CGPoint = CGPointMake(0, 0) 
var startFrame:CGRect! 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    // Initialization code 
    var panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:") 
    self.gestureRecognizers = [panRecognizer] 

    self.backgroundColor = UIColor.redColor() 

    //add UITextView 
    var text = UITextView() 
    text.backgroundColor = UIColor.brownColor() 
    text.text = "This is a test" 
    text.frame = CGRectMake(self.center.x, self.center.y, 40, 40) 
    self.addSubview(text) 
} 

required init(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

func detectPan(gesture:UIPanGestureRecognizer) { 
    switch(gesture.state) 
    { 
     case .Began: 
      self.startFrame = gesture.view?.frame 
     case .Changed: 
      let newCoord = gesture.locationInView(gesture.view) 
      let dX = newCoord.x 
      let dY = newCoord.y 
      let center = CGPointMake((gesture.view?.frame.origin.x)! + dX, (gesture.view?.frame.origin.y)! + dY) 
      gesture.view?.center = center 
     case .Ended: 
      gesture.view?.frame = self.startFrame 
      print("ended") 
     default: 
      print("will not handel") 

    } 
} 

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    // Promote the touched view 
    //self.superview?.bringSubviewToFront(self) 

    // Remember original location 
    lastLocation = self.center 
} 
}