6

I've got the following structure for example:

Start

I want to rotate my label by 270degrees to achieve this:

End

via CGAffineTransform.rotated next way:

    credentialsView.text = "Developed in EVNE Developers"
    credentialsView.transform = credentialsView.transform.rotated(by: CGFloat(Double.pi / 2 * 3))

but instead of expected result i've got the following:

enter image description here

So, what is the correct way to rotate view without changing it's bounds to square or whatever it does, and keep leading 16px from edge of screen ?

I tried a lot of ways, including extending of UILabel to see rotation directly in storyboard, putted dat view in stackview with leading and it also doesn't helps, and etc.

Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
Nikita Yankov
  • 145
  • 1
  • 9
  • This page might have the answer you need: https://stackoverflow.com/questions/8275882/one-step-affine-transform-for-rotation-around-a-point – dijipiji May 10 '18 at 08:09

1 Answers1

7

Here is the solution which will rotate your label in an appropriate way forth and back to vertical-horizontal state. Before running the code, set constraints for your label in storyboard: leading to 16 and vertically centered.

Now check it out:

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    // Your leading constraint from storyboard, initially set to 16
    @IBOutlet weak var leadingConstraint: NSLayoutConstraint!

    var isHorizontal: Bool = true
    var defaultLeftInset: CGFloat = 16.0

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .white
        label.text = "This is my label"
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
    }

    @objc func tapAction() {
        if self.isHorizontal {
            // Here goes some magic
            // constraints do not depend on transform matrix, 
            // so we have to adjust a leading one to fit our requirements
            leadingConstraint.constant = defaultLeftInset - label.frame.width/2 + label.frame.height/2
            self.label.transform = CGAffineTransform(rotationAngle: .pi/2*3)
        }
        else {
            leadingConstraint.constant = defaultLeftInset
            self.label.transform = .identity
        }
        self.isHorizontal = !self.isHorizontal
    }
}
Vadim Popov
  • 1,177
  • 8
  • 17
  • 1
    Awesome! That did the trick, thanks. P.S. Can't you share a literature / resource where u find that way (i mean not your example) ? Or it's just your knowledge and experience :thinking: – Nikita Yankov May 10 '18 at 08:56
  • 1
    @NikitaYankov that's just exp:) UIKit stuff is pretty friendly to learn, take some time to practice and play around. Official documentation is often helpful as well – Vadim Popov May 10 '18 at 08:59