-1

I'm very new to Swift and really need some help out here. I have a UIImageView with the image of arrow on it. I want the arrow to randomly change its direction on a button click in only THREE directions: top, right and bottom. I figured out to rotate the UIImageView using CGAffineTransform, but how can I ?

  1. Exclude the left direction from the rotation?
  2. Make the arrow change its direction (top, right and bottom) randomly ?

here's a screen I work with

vivekDas
  • 1,248
  • 8
  • 12
Dary
  • 3
  • 2
  • Please share your attempts so far – JoGoFo Aug 10 '18 at 07:53
  • Well, I came up with a thought to create an Enum RotationDirection with three cases: top, right, bottom. And I also have a line of code for CGAffineTransform which doesn't have any connection with the Enum so far. self.arrowImageView.transform = self.arrowImageView.transform.rotated(by: CGFloat((Double.pi / 2))) This line of code finely rotates the image in the UIImageView, but in all 4 directions (obviously). And here I stuck ;) – Dary Aug 10 '18 at 07:56
  • Kindly refer to this question https://stackoverflow.com/questions/40882487/how-to-rotate-image-in-swift This might help you in some way – Saurabh Aug 10 '18 at 08:00

2 Answers2

0

generate a random nuumber:

 let randomInt = Int.random(in: 0..<3)

  switch randomInt {
    case 0:
        rotateRight()
    case 1:
        rotateUp()
    case 2:
        rotateDown()
    default:
        rotateWhatever()
    }
shayegh
  • 302
  • 1
  • 9
0

Hope this will helps you:

    let degree = [Double.pi / 2, Double.pi, Double.pi * 2]
    let randomIndex = Int(arc4random_uniform(UInt32(degree.count)))
    UIView.animate(withDuration: 1.0) {
        self.imageView.transform = CGAffineTransform(rotationAngle: CGFloat(degree[randomIndex]))
    }

enter image description here

iVarun
  • 6,496
  • 2
  • 26
  • 34
  • Thanks! That's very helpful. The only one thing is why the arrow doesn't change its rotation on EVERY tap? Sometimes it stands still even after the button click... – Dary Aug 10 '18 at 08:23
  • @Dary coz it is selecting random value from array. – iVarun Aug 10 '18 at 08:24
  • So by this logic sometimes the direction just stays the same, that's why there's no rotation on a button click. Is that the case? – Dary Aug 10 '18 at 08:29
  • Thank you very much! The last question to you though :) The arrow in your example still rotates to the left direction. However, I need to exclude this direction from the rotation. How can I do this? – Dary Aug 10 '18 at 08:36
  • @Dary remove first object from array. – iVarun Aug 10 '18 at 08:38
  • @Dary could you please approve and upvote my answer if it helps you. This will also helps other to find correct answer. – iVarun Aug 10 '18 at 08:45
  • 1
    Thanks for your help. Appreciate! – Dary Aug 10 '18 at 08:48