objective-c - 尝试加载有关方向更改的新 View

标签 objective-c ios

我正在尝试在 Xcode 中创建一个应用程序,当手机从一个方向旋转到另一个方向时,它会切换到一个新 View 。

这里是“switchviewcontroller.h”文件代码:

#import <UIKit/UIKit.h>

@interface SwitchViewController : UIViewController {

}

-(IBAction)switchview:(id)sender;

@end

这里是“switchviewcontroller.m”文件代码:

#import "SwitchViewController.h"
#import "secondview.h"

@implementation SwitchViewController

-(IBAction)switchview:(id)sender {}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
       (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {    
        [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
    }

}

它在 iPhone 模拟器中运行没有错误,但是,当我旋转时它不会加载新 View 。对于初学者,我认为我需要应用程序以横向模式打开,我不知道该怎么做,但它仍然无法正常工作,我认为它与代码的“initWithNibName”部分有关,因为我有 .xib 文件而不是 .nib 文件。谁能帮我解决这两件事?谢谢。

最佳答案

您没有推送或展示任何东西,您只是在初始化 View 。

secondview *second = [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:second animated:YES];

不过,这不是展示新观点的好地方。

如果你想以不同的方向显示相同的 View ,试试这个:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || 
        (interfaceOrientation == UIInterfaceOrientationLandscapeRight))){

        self.view = landscape;

    }else if(((interfaceOrientation == UIInterfaceOrientationPortrait) || 
              (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))){

        self.view = portrait;

    }

    return YES;
}

请注意,portraitlandscape 是您在 header 中定义并通过 Interface Builder 连接的 UIViewController 中的 UIView。


此外,这些需要在 .h/.m 中:

.h

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView portrait;
@property(nonatomic,retain) UIView landscape;

.m

@synthesize portrait,landscape;

关于objective-c - 尝试加载有关方向更改的新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4762967/

相关文章:

ios - iPhone 应用程序无法在 iPad 上运行

iphone - subview 内的 touchesMoved 检测

ios - 如何检查 UICollectionView 有图像

ios - Libgdx 导出为 ios 应用程序

ios - 与服务器的安全通信 - 解决方案

ios - Mapbox - 计算 MGLPointAnnotation 是否在 MGLPolygon 内

objective-c - UITextField 使部分不可编辑

ios - 错误 "Application windows are expected to have a root view controller"(iOS)

ios - 在 Swift 中连续绘制 UIBezierPath 期间消除滞后延迟

iphone - UITableView 失去选中状态 iOS