Reputation: 993
Can you help me please to move my image random on my View when I click it ? I need to use UIView Animations (is required) and when the UIImageView is reaching the random destination on the screen it should change the color/image from inside.
Here is my code:
import UIKit
import QuartzCore
// ---- Is required to use UIView Animation ------
class FirstViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: "1.png") // the second image is named "2.png"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let touchLocation = touch.location(in: view)
let leftCorner = CGPoint(x: touchLocation.x + 48, y: touchLocation.y + 48)
imageView.center = leftCorner
}
}
Thanks in advance !
Upvotes: 0
Views: 1228
Reputation: 235
Here's my solution:
import UIKit
class ViewController: UIViewController {
let imageViewWidth = CGFloat(100)
let imageViewHeight = CGFloat(100)
let colors = [UIColor.red, UIColor.blue, UIColor.gray, UIColor.brown, UIColor.green]
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.frame = CGRect(
x: view.bounds.width/2 - imageViewWidth/2,
y: view.bounds.height/2 - imageViewHeight/2,
width: imageViewWidth,
height: imageViewHeight
)
addTapRecognizerToImageView()
}
func addTapRecognizerToImageView() {
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
}
@objc func handleTap() {
let maxX = view.frame.maxX-imageViewWidth
let maxY = view.frame.maxY-imageViewHeight
let randomX = arc4random_uniform(UInt32(maxX)) + 0
let randomY = arc4random_uniform(UInt32(maxY)) + 0
UIView.animate(withDuration: 0.5) {
self.imageView.frame = CGRect(
x: CGFloat(randomX),
y: CGFloat(randomY),
width: self.imageViewWidth,
height: self.imageViewHeight
)
}
let randomColor = Int(arc4random_uniform(4) + 0)
imageView.backgroundColor = colors[randomColor]
}
}
Upvotes: 2