Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate iOS label and make it stick to edge of screen?

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.

like image 551
Nikita Yankov Avatar asked May 10 '18 08:05

Nikita Yankov


1 Answers

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
    }
}
like image 50
Vadim Popov Avatar answered Oct 12 '22 02:10

Vadim Popov