Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to rotate an IBDesignable UIButton using Swift?

Tags:

swift

How to make an IBDesignable component that has an angle: CGFloat property that rotates the view

import UIKit

@IBDesignable
class MyB: UIButton {
    @IBInspectable
    var angle: CGFloat = 0 {
        didSet {
            //What to put here?
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        // Initialization code
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

I tried

self.transform = CGAffineTransformMakeRotation(angle)

but it doesn't work

like image 496
ielyamani Avatar asked Jul 09 '14 18:07

ielyamani


1 Answers

You should create CustomButton inherited from UIButton

import UIKit

@IBDesignable
class CustomButton: UIButton {

    @IBInspectable var rotation: Double = 0 {
        didSet {
            rotateButton(rotation: rotation)
        }
    }

    func rotateButton(rotation: Double)  {
        self.transform = CGAffineTransform(rotationAngle: CGFloat(.pi/2 + rotation))
    }
}

You will get following output,

enter image description here

like image 109
PPL Avatar answered Sep 28 '22 10:09

PPL