0

Is it possible to reset the element to the same % position (distance from x = 0 axis) for both landscape and portrait mode? If yes could you show me how? Also since i am a newbie to Swift if you notice any bad code mistake please DO notify me in order to get better.Thanks in advance

This is my ViewController:

import UIKit

    class ViewController: UIViewController
    {
        @IBOutlet var initView: UIView!
            {
                didSet
                {                
                    initView.addGestureRecognizer(UIPanGestureRecognizer(target: initView, action: "panRecognize:"))
                }
            }


    }

This is my View:

import UIKit

class InitView: UIView {



  private  struct location
    {
        static var movableRect : CGPoint = CGPoint.zero
        static var movableRectSize : CGSize = CGSize(width: location.screensize.width*0.2, height: location.screensize.height*0.05)
        static var screensize : CGRect = UIScreen.mainScreen().bounds
    }


    func panRecognize(gesture : UIPanGestureRecognizer)
    {
        let state = gesture.state
        switch state
        {
        case .Ended:
            fallthrough
        case .Changed:
            gesture.setTranslation(gesture.locationInView(self), inView: self)
            location.movableRect.x =    gesture.translationInView(self).x - location.movableRectSize.width/2
            location.movableRect.y =    gesture.translationInView(self).y - location.movableRectSize.height/2
            setNeedsDisplay()
        default:
            break
        }
    }

     private   func makeMovableRect(arg: CGPoint)
    {
        let path = UIBezierPath(rect: CGRect(origin: arg, size: location.movableRectSize))
        UIColor.purpleColor().set()
        path.fill()
    }

        override func drawRect(rect: CGRect)
    {

        if location.movableRect != CGPoint(x: 0, y: 0)
        {
            makeMovableRect(location.movableRect)

        }
    }

}

What my program does is simply transfer a small Rect anywhere the user taps and keeps pressing.When the user removes touching the screen the object remains to the last location(default behavior).After i change the rotation though since the bounds change i want it to redraw to the same % location it was in the portrait mode.Let me show you some photos to help you out. Perhaps it's really easy but looking online for a solution got me to try out got me to use the bool value of UIDevice (isLandscape) and i kinda messed things up.

Portrait Mode

What i want it to look like in landscape mode

Korpel
  • 2,432
  • 20
  • 30

1 Answers1

0

You can use a function like

func pointForBounds(point: CGPoint,originalBounds: CGRect)->CGPoint{
        return CGPointMake(originalBounds.origin.x/self.bounds.origin.x*point.x, originalBounds.origin.y/self.bounds.origin.y*point.y)
    }

to update the origin of your rect during changes in the bounds of your view

beyowulf
  • 15,101
  • 2
  • 34
  • 40