我需要在屏幕上有两个视图用于拖动(完成白色UIPanGestureRecogniser
)和它们之间的连接线,所以当我自由移动视图时,线条保持连接(就像视图之间的绳索)。并测量该线的角度。
到目前为止这是我的代码
var rect1:UIView!
var rect2:UIView!
override func viewDidLoad() {
super.viewDidLoad()
// create my two views
rect1 = UIView(frame: CGRect(x: 50, y: 150, width: 40, height: 40))
rect1.backgroundColor = UIColor.orange
self.view.addSubview(rect1)
rect2 = UIView(frame: CGRect(x: 200, y: 150, width: 40, height: 40))
rect2.backgroundColor = UIColor.yellow
self.view.addSubview(rect2)
// and the UIPanGestureRecognizer objects
let gesture1 = UIPanGestureRecognizer(target: self, action: #selector(dragView))
rect1.addGestureRecognizer(gesture1)
let gesture2 = UIPanGestureRecognizer(target: self, action: #selector(dragView))
rect2.addGestureRecognizer(gesture2)
// add mi connecting line between
func addLine(fromPoint start: rect1.center, toPoint end:rect2.center)
}
// create the func for moving the views
func dragView(_ sender: UIPanGestureRecognizer)
{
let point = sender.location(in: self.view)
let theDraggedView = sender.view!
theDraggedView.center = point
}
// and the func for line creation
func addLine(fromPoint start: CGPoint, toPoint end:CGPoint)
{
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.red.cgColor
line.lineWidth = 2
line.lineJoin = kCALineJoinRound
self.view.layer.addSublayer(line)
}
}
这里我有股票!! 如果我在dragView中再次使用addline func,则创建数百行。 并且不知道下一步该做什么
答案 0 :(得分:0)
这是因为当你一次又一次地调用addLine
函数时你没有删除前一行。
要删除上一行,请在顶部将var line = CAShapeLayer()
声明为类,这样您就可以获得之前绘制的行,然后无论何时调用addLine
函数,只需在开始时从superview中删除上一行,如:< / p>
line.removeFromSuperlayer()
您的完整代码将是:
import UIKit
class ViewController: UIViewController {
var rect1:UIView!
var rect2:UIView!
var line = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
rect1 = UIView(frame: CGRect(x: 50, y: 150, width: 40, height: 40))
rect1.backgroundColor = UIColor.orange
self.view.addSubview(rect1)
rect2 = UIView(frame: CGRect(x: 200, y: 150, width: 40, height: 40))
rect2.backgroundColor = UIColor.yellow
self.view.addSubview(rect2)
// and the UIPanGestureRecognizer objects
let gesture1 = UIPanGestureRecognizer(target: self, action: #selector(dragView))
rect1.addGestureRecognizer(gesture1)
let gesture2 = UIPanGestureRecognizer(target: self, action: #selector(dragView))
rect2.addGestureRecognizer(gesture2)
addLine(start: rect1.center, toPoint:rect2.center)
}
func dragView(_ sender: UIPanGestureRecognizer) {
let point = sender.location(in: self.view)
let theDraggedView = sender.view!
theDraggedView.center = point
addLine(start: rect1.center, toPoint:rect2.center)
}
func addLine(start: CGPoint, toPoint end:CGPoint) {
line.removeFromSuperlayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.red.cgColor
line.lineWidth = 2
line.lineJoin = kCALineJoinRound
self.view.layer.addSublayer(line)
}
}