根据方向

时间:2016-03-03 14:57:47

标签: ios xcode swift xcode-storyboard

目前我已经设置了针对横向模式优化的故事板。起初我认为我只允许横向定位。然而,在此过程中,我决定允许两种选择。我现在所做的是创建一个新的故事板,其中包含纵向方向的布局。

我是这样做的,因为视图将完全不同地设置。有没有办法在运行时根据方向在故事板之间切换,或者是我在做什么非常糟糕的练习,并建议采取不同的方向。

我认为使用xib文件会导致重复的代码,所以我可能完全错了。我很想知道是否可以根据方向切换故事板,如果可以,如何实现这一点。如果这是一个很好的做法。我现在设置的方式是故事板都使用相同的视图控制器,因此它们都使用相同的方法/出口

根据Haroldo Gondim的名字进行编辑

我把它放在AppDelegate的didFinishLaunchingWithOptions中。

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

然后我在app delegate类中也有这个功能

func rotated(){
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
    {
        storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    }

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
    {
        storyboard = UIStoryboard.init(name: "portrait", bundle: nil)
    }
    //self.window?.rootViewController = storyboard?.instantiateInitialViewController()
    storyboard?.instantiateViewControllerWithIdentifier("ViewController")
    //self.window?.makeKeyAndVisible()
}

我还尝试使用instantiateInitialViewController

但无论我尝试什么都不会改变故事板。它确实按照它应该的方式进入if语句

4 个答案:

答案 0 :(得分:2)

Xcode storyboard对于这个称为大小的类具有很好的功能。起初它有点难以理解,但希望教程可以帮助

http://www.raywenderlich.com/113768/adaptive-layout-tutorial-in-ios-9-getting-started

答案 1 :(得分:2)

内置的大小类允许您在同一个故事板上构建完全不同的UI。运行时将为当前设备/方向(大小类)选择适当的场景/控件,并自动布局(利用AutoLayout)。查看本地Xcode帮助中的大小类功能,因为它非常易于使用。基本上,布局所有尺寸的整个场景,然后在布局新场景之前更改尺寸等级(以引用新的方向)(如果您愿意,可以使用所有新UI)...

关联新用户界面,您已完成。

问:您是否会获得大量代码副本?

响应

  

如果要使用大小类重新排列UI元素,那么就可以   使用多个VC。如果您正在创建新的UI元素,那么您需要添加IBOutlets和查看操作代码,就像任何新的一样   控件通常会添加到现有的ViewController中。运用   自动布局和大小类可以重新排列现有视图而无需   任何代码调整都没有。布局更改隐藏在内部   Storyboard文件为xml。如果右键单击故事板文件   你可以打开源代码看看。要还原右键单击和   打开界面构建器。

答案 2 :(得分:0)

View(df)可以让您重新排列不同方向的视图。

对于不同的功能和元素,你应该使用Autolayout,按照教程@Blakusl链接,非常好。

答案 3 :(得分:0)

检查设备方向并根据方向实例化故事板。

UIStoryboard *storyboard;

if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) || ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft))
{
    storyboard = [UIStoryboard storyboardWithName:@"StoryboardLandscape" bundle: nil];    
} else {
    storyboard = [UIStoryboard storyboardWithName:@"StoryboardPortrait" bundle: nil];
}

[storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentifier"];

修改

在每个视图控制器中,您必须添加标识符

Identifier