[英]how to transfer coordinates to display a imageview with long tap
我正在尝试完成一项任务。 单击长按时,我需要显示图像。 问题是我不知道如何在我点击的地方显示它。
我的代码:
let longRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressHappened))
view.addGestureRecognizer(longRecognizer)
@objc func longPressHappened() {
let imageView = UIImageView(image: UIImage(named: "location")!)
imageView.frame = CGRect(x: 200, y: 100, width: 24, height: 42)
CSimageView.addSubview(imageView)
}
我找到了这段代码,但我不明白如何在我的问题中应用它:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: view)
print(position)
}
}
现在长按可以工作,但显示在代码中指示的坐标处,对于 x,数字是 200,对于 y,数字是 100。我需要图片出现在我点击的位置。
试试下面的代码,你长按那里会添加一个图像。
我在视图中添加了手势和图像。
override func viewDidLoad() {
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
self.view.addGestureRecognizer(longPressRecognizer)
}
//This method will get called when you long press
@objc func longPressed(gesture: UILongPressGestureRecognizer)
{
//get location of gesture
let tapLocation = gesture.location(in: self.view)
let imageView = UIImageView(image: UIImage(named: "location"))
//Set x and y of tapped location
imageView.frame = CGRect(x: tapLocation.x, y: tapLocation.y, width: 24, height: 24)
print("longpressed")
//Add image When lognpress is finish
if gesture.state == .ended {
self.view.addSubview(imageView)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.