#以UIButton为例子 #1.首先创建一个Button UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.backgroundColor = [UIColor clearColor]; btn.frame = CGRectMake(100, 100, 40, 40); [btn addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside]; [btn setBackgroundImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal]; [self.view addSubview:btn]; #2.需要一个集合 //添加属性 @property (nonatomic, strong) NSMutableSet *btnSet; //初始化 _btnSet = [[NSMutableSet alloc]init]; //添加元素 [_btnSet addObject:btn]; #3.监听设备方向 //在VieDidLoad中添加 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kNotificationOrientationChange" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:@"kNotificationOrientationChange" object:nil]; //接着实现这些方法 #pragma mark ---------rotate(only when this controller is presented, the code below effect)------------- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationOrientationChange" object:nil]; return (interfaceOrientation == UIInterfaceOrientationPortrait); } #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0 //iOS6+ - (BOOL)shouldAutorotate{ [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationOrientationChange" object:nil]; return NO; } - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { // return [UIApplication sharedApplication].statusBarOrientation; return UIInterfaceOrientationPortrait; } #endif #4.实现监听方法 -(void)orientationDidChange:(NSNotification *)noti{ if (!_btnSet || _btnSet.count <= 0) { return; } [_btnSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) { UIButton *btn = ([obj isKindOfClass:[UIButton class]] ? (UIButton*)obj : nil); if (!btn) { *stop = YES; return ; } btn.layer.anchorPoint = CGPointMake(0.5, 0.5); CGAffineTransform transform = CGAffineTransformMakeRotation(0); switch ([UIDevice currentDevice].orientation) { case UIDeviceOrientationPortrait://1 { transform = CGAffineTransformMakeRotation(0); break; } case UIDeviceOrientationPortraitUpsideDown://2 { transform = CGAffineTransformMakeRotation(M_PI); break; } case UIDeviceOrientationLandscapeLeft://3 { transform = CGAffineTransformMakeRotation(M_PI_2); break; } case UIDeviceOrientationLandscapeRight://4 { transform = CGAffineTransformMakeRotation(-M_PI_2); break; } default: break; } [UIView animateWithDuration:0.3f animations:^{ btn.transform = transform; }]; }]; } ###接着就运行吧~~~ 是否发现怎么转屏幕button的方向都没变,仔细读代码 #pragma mark ---------rotate(only when this controller is presented, the code below effect)------------- 相信你已经明白问题所在了~ 分享到: 微信 微博 豆瓣 Previous 多些时间能少写些代码 Next FMDB的使用 FEATURED TAGS sample post images test Blog FRIENDS XenonChau Onery的简书