6

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

ZYiOS
  • 5,204
  • 3
  • 39
  • 45
ielyamani
  • 17,807
  • 10
  • 55
  • 90
  • Define "doesn't work". The fact that you've declared this as IBDesignable isn't relevant to the question. – NRitH Jul 10 '14 at 02:51
  • "doesn't work" meaning when I change the angle in the inspector in Interface Builder, the UIButton's frame doesn't rotate – ielyamani Jul 10 '14 at 10:10
  • 1
    This seems like a genuine bug as of Xcode 6 beta 4, so I submitted a test project as bug report 17764377 to Apple. Views will rotate correctly when the app is run, but CGAffineTransformMakeRotation has no effect in Live View regardless of various refreshes I tried to force. – kasplat Jul 23 '14 at 18:08
  • Possible duplicate of [@IBInspectable not updating Story Board](http://stackoverflow.com/questions/33545455/ibinspectable-not-updating-story-board) – ZYiOS Dec 15 '15 at 07:35
  • look ... http://stackoverflow.com/a/37300130/294884 – Fattie May 18 '16 at 23:11

1 Answers1

4

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

PPL
  • 6,357
  • 1
  • 11
  • 30