gpt4 book ai didi

ios - 尝试使用 UIPanGesture 在 UIView 上绘图

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

class theView: UIView
{
var kl = 1
var px : CGFloat = 0.0
var py : CGFloat = 0.0

override func drawRect(rect: CGRect)
{
color()
setNeedsDisplay()
}


func move(gesture : UIPanGestureRecognizer)
{
let state = gesture.state
switch state
{
case .Began: print("started")
case .Ended: fallthrough
case .Changed:
let translation = gesture.translationInView(self)
px = translation.x
py = translation.y
print("x:\(px), y:\(py)")
default: break
}
}
func color()
{
let path = UIBezierPath()
path.moveToPoint(CGPointZero)
path.addLineToPoint(CGPoint(x: px, y: py))
UIColor.blueColor().set()
path.stroke()
self.setNeedsDisplay()
}
}

这是我认为的代码。我错过了什么并且它没有显示在我的屏幕上?它确实识别了我的移动,因为 pxpy 更改了值。这是更大项目的一部分,所以请告诉我如果有任何编译错误..

我的 View Controller 是:

class ViewController: UIViewController, Moveable
{
var k = 1

@IBOutlet weak var sdasd: theView!
{
didSet
{
sdasd.k = self
sdasd.addGestureRecognizer(recognizer)
let panRecognizer = UIPanGestureRecognizer(target: sdasd, action: "move:")
sdasd.addGestureRecognizer(panRecognizer)
sdasd.setNeedsDisplay()
}
}

还有人可以告诉我到底需要把 setNeedsDisplay() 放在哪里吗?我需要将它放在我的 View Controller 中吗?我的超控抽屉?谢谢。如果你需要什么就告诉我。我希望它能在我看来划清界限。就像绘画一样

最佳答案

setNeedsDisplay() 通知您的 UIView 它需要在下一个绘制周期内重新绘制。在 drawRect 函数中,您指定应在 UIView 上绘制的内容。您希望每次在 GestureRecognizer 中处于 Changed 状态时更改 UIView 的外观,因此这也是您需要通知 View 重绘的地方,即调用 setNeedsDisplay(),而且仅在那里。

编辑

我相信这是您正在寻找的类(class)

class theView: UIView
{
var kl = 1
var px : CGFloat = 0.0
var py : CGFloat = 0.0
var pxStart : CGFloat = 0.0
var pyStart : CGFloat = 0.0

override init(frame: CGRect) {
super.init(frame: frame)
let panRecognizer = UIPanGestureRecognizer(target: self, action: "move:")
self.addGestureRecognizer(panRecognizer)
}

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

override func drawRect(rect: CGRect)
{
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: pxStart, y: pyStart))
path.addLineToPoint(CGPoint(x: pxStart+px, y: pyStart+py))
UIColor.blueColor().set()
path.stroke()
}

func move(gesture : UIPanGestureRecognizer)
{
let state = gesture.state
switch state
{
case .Began:
pxStart = gesture.locationInView(self).x
pyStart = gesture.locationInView(self).y
case .Ended: fallthrough
case .Changed:
let translation = gesture.translationInView(self)
px = translation.x
py = translation.y
self.setNeedsDisplay()
default: break
}
}
}

关于ios - 尝试使用 UIPanGesture 在 UIView 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32720450/

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