gpt4 book ai didi

ios - 可拖动的 UITextView

转载 作者:行者123 更新时间:2023-11-30 14:08:40 25 4
gpt4 key购买 nike

我需要创建一个可拖动的 UITextView。我设法创建了一个可拖动 View ,并尝试添加一个 TextView 作为 subview ,但它不起作用,TextView 不可编辑,并且它没有出现在 View 内部,而是出现在 View 下方。

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

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

最佳答案

试试这个代码,我更新了您的 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
}
}

关于ios - 可拖动的 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32025121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com