yoavlt / LiquidFloatingActionButton

Material Design Floating Action Button in liquid state
MIT License
3.85k stars 468 forks source link

Orientation changes #41

Open polis80cy opened 8 years ago

polis80cy commented 8 years ago

How can I make the button respect orientation changes if I created it programmatically and not via the storyboard? I don't see this being supported.

Thanks.

vijaysanghavi commented 8 years ago

You can do some thing like below:

Step 1:

var isPortrait: Bool = true
var mainScreen = UIScreen.mainScreen()

override func viewDidLoad()
    {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationDidChange", name: UIDeviceOrientationDidChangeNotification, object: nil)

        self.floatingActionButtonSetUp(mainScreen.bounds.width,height: mainScreen.bounds.height)
    }

Step 2:

func floatingActionButtonSetUp(width:CGFloat, height:CGFloat)
    {
        let createButton: (CGRect, LiquidFloatingActionButtonAnimateStyle) -> LiquidFloatingActionButton = { (frame, style) in
            let floatingActionButton = LiquidFloatingActionButton(frame: frame)
            floatingActionButton.animateStyle = style
            floatingActionButton.dataSource = self
            floatingActionButton.delegate = self
            return floatingActionButton
        }

        let cellFactory: (String) -> LiquidFloatingCell = { (iconName) in
            return LiquidFloatingCell(icon: UIImage(named: iconName)!)
        }
        cells.append(cellFactory("ic_cloud"))
        cells.append(cellFactory("ic_system"))
        cells.append(cellFactory("ic_place"))

        let navigationBarHeight: CGFloat = 64
        let padding: CGFloat = 72
        let floatingFrame = CGRect(x: width - padding , y: height - padding - navigationBarHeight, width: 56, height: 56)

        if isPortrait == true
        {
            bottomRightButton  = createButton(floatingFrame, .Up)
        }
        else
        {
            bottomRightButton  = createButton(floatingFrame, .Left)
        }

        self.view.addSubview(bottomRightButton)
    }

Step 3:

 func orientationDidChange()
    {
        if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
        {
            isPortrait = false
        }
        else
        {
            isPortrait = true
        }

        cells.removeAll()
        bottomRightButton.removeFromSuperview()
        self.floatingActionButtonSetUp(mainScreen.bounds.width,height: mainScreen.bounds.height)
    }