Search code examples
objective-cuitableviewuibuttonuiinterfaceorientation

How to detect UIInterfaceOrientation immediately when device change Orientation (Portrait,Landscape)


I create UITableViewCell and i want to change button position when user change landscape to portrait or portrait to landscape i try to check same this code but it not auto detect.

    - CellForRowAtIndexPath
{
    if (UIDeviceOrientationIsPortrait(self.interfaceOrientation))
    {
        [Button setFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width - 50, 20, 50, 50)];
    }else
    {
        [Button setFrame:CGRectMake([[UIScreen mainScreen] bounds].size.height - 70, 20, 50, 50)];
    }
}

Solution

  • One way is to add these to your viewController:

    - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
        // will rotate
    }
    - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
        // will animate rotation
    }
    - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
        // done rotating
    }
    

    Or, you can register for notifications:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationDidChange:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:self];