可拖动的UITextView

时间:2015-08-15 13:19:40

标签: ios swift uitextview draggable

我需要创建一个可拖动的UITextView。 我设法创建一个可拖动的视图,我试图添加一个TextView作为子视图,但它不起作用,TextView不可编辑,它没有出现在视图内但在它下面。

这是我创建的自定义视图代码:

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添加到可拖动视图?

1 个答案:

答案 0 :(得分: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
}
}