簡體   English   中英

Xcode swift 3 不知道如何在我單擊的位置顯示圖像

[英]Xcode swift 3 don't know how to display an image where I click

我是一名新程序員,遇到了一個問題。 我想要一個圖像出現在我點擊的屏幕上。 因此,例如我單擊屏幕頂部我希望圖像顯示在那里然后如果我單擊屏幕底部我希望圖像去那里,但我不希望第一張圖像消失我只是想添加另一個。 使用 swift 3 謝謝

您可以通過以這種方式覆蓋UIViewController touchesBegan方法來簡單地實現這一點:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM