Search code examples
iosuiviewright-to-leftrectangles

ios draw rectangle with top right corner


I am trying to make a rect which is drawn using it's top right corner (x,y) instead of the usual top left. I tried scaling by -1, but that didn't do the work.

I need it because I am developing an app for RTL locale.


Solution

  • If you use auto layout, you can use the leading and trailing constraints (rather than left and right constraints) and the animation will automatically be adjusted for the target language. For example, consider the following simplistic demo that overlays a "curtain" view, and then, two seconds later "pulls it aside" by animating the trailing constraint:

    let curtain = UIView()
    curtain.backgroundColor = .darkGrayColor()
    curtain.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(curtain)
    
    let trailingConstraint = curtain.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor)
    
    NSLayoutConstraint.activateConstraints([
        curtain.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
        curtain.topAnchor.constraintEqualToAnchor(view.topAnchor),
        curtain.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor),
        trailingConstraint
    ])
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
        trailingConstraint.constant = -self.view.bounds.size.width
        UIView.animateWithDuration(0.5) {
            self.view.layoutIfNeeded()
        }
    }
    

    If your project's localization is a LTR language, it will animate the pulling back of this "curtain" from the right edge.

    But if you project's localization is a RTL language, such as shown below, then it will animate the pulling of this "curtain" from the left edge:

    enter image description here