找到你要的答案

Q:Draggable UITextView Not Responding

Q:Draggable UITextView没有回应

I have created a custom UITextView that need to be draggable, this is the code I use:

class DraggableView: UITextView {

var lastLocation:CGPoint = CGPointMake(0, 0)

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

    self.editable = true
    self.selectable = true
    self.backgroundColor = UIColor.redColor()
}

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
}
}

The shows up but the problem is that I can't write anything or interact with it, I can only move it.

What is the problem?

我创建了一个自定义UITextView需要拉动的,这是我用的代码:

class DraggableView: UITextView {

var lastLocation:CGPoint = CGPointMake(0, 0)

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

    self.editable = true
    self.selectable = true
    self.backgroundColor = UIColor.redColor()
}

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>, 具有Event event: UIEvent) {
    // Promote the touched view
    //self.superview?.bringSubviewToFront(self)

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

显示出来,但问题是,我不能写任何东西或与它互动,我只能移动它。

问题是什么?

answer1: 回答1:

I think you should replace the code

self.gestureRecognizers = [panRecognizer]

with

self.addGestureRecognizer(panRecognizer)

I think there must be a gesture whick belongs to gestureRecognizers to tell the textView to become first responder.

我认为你应该更换代码

self.gestureRecognizers = [panRecognizer]

具有

self.addGestureRecognizer(panRecognizer)

我认为必须有一个姿态,它属于gesturerecognizers告诉TextView成为第一响应者。

ios  swift  uitextview  draggable