我是一个新程序员,遇到了一个问题。我希望在我单击的屏幕上显示一个图像。例如,我单击屏幕顶部,我希望图像显示在那里,然后如果我单击屏幕底部,我希望图像转到那里,但我不希望第一个图像消失,我只想添加另一个。使用 swift 3谢谢
您可以通过以这种方式覆盖touchesBegan
UIViewController
方法来简单地实现这一点:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touch = touches.first else { return }
let touchLocation = touch.location(in: self.view) // Get the location of the touch
let image = UIImage(named: "anImage") // Create a UIImage instance
let imageView = UIImageView(image: image) // Create a UIImageView with your image
imageView.contentMode = .scaleAspectFit
// Set the position of your image to be where the user touched
imageView.frame = CGRect(x: touchLocation.x,
y: touchLocation.y,
width: 100,
height: 100)
self.view.addSubview(imageView) // Add the image to the view
}