React Native方向无法工作 || 在iOS上锁定

4

我使用React Native创建了一个应用程序。我制作的所有页面都是为竖屏模式设计的,除了一个页面。该页面可通过按下按钮进行访问,然后导航到该页面,所以我无法在Xcode上锁定方向。

我安装了这个包,我可以在安卓上完美运行它。

import Orientation from 'react-native-orientation';

我在IOS模拟器上测试时发现每个页面都可以横屏显示。

我在每个页面的componentdidmount生命周期函数中添加了这行代码,但是没有任何改变。

componentDidMount() {
   

    Orientation.lockToPortrait()
...
}

我该怎么办?


有人可以帮忙锁定屏幕方向吗? - masterAvatarr
你的意思是什么: “页面可访问性来自按钮 onPress,然后导航到页面,因此我无法在Xcode中锁定方向。” 如果你使用的是纯React Native,你可以在Info.plist上进行简单的锁定。 - FreakyCoder
Oooo @FreakyCoder,我是你的粉丝,顺便说一下,我正在使用你的一两个软件包 :)。基本上我有10页,其中9页是纵向屏幕,1页是横向屏幕。如果我锁定为纵向,则横向页面无法正常工作。 - masterAvatarr
哦,我明白了。你使用的是expo还是纯React Native?根据这个,我可以帮助你。谢谢你,@masterAvatarr :) - FreakyCoder
Abi,这个弹跳效果和任何组件的动画效果都非常棒,真的很不错。我正在使用纯React Native。 - masterAvatarr
2个回答

4

你好,@masterAvatarr,

我相信这就是你要找的内容,如果你需要其他的,请告诉我 :) 我们可以实现它。

我为你做了一个简单的例子。

https://github.com/WrathChaos/react-native-portrait-locker-example

我使用了React Native Orientation Locker Library

重要部分如下:

  • 确保你手动链接了库(检查AppDelegate.m)
  • 你需要根据你的用例制定解锁和锁定纵向模式的逻辑

请查看HomeScreenDetailScreen


import Orientation from "react-native-orientation-locker";


React.useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      // The screen is focused
      // Call any action
      Orientation.unlockAllOrientations();
      Orientation.lockToPortrait();
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

注意: Github 存储库中有一个小的 GIF 演示。


谢谢您的回答,但我几乎在每个页面都使用类组件:D。我正在使用类组件,Hocam focus listeneri用于在页面重新加载时进行刷新等操作。 - masterAvatarr
您可以在类组件上使用此逻辑,使用componentDidUpdate,并检查导航是否相同。无论是类组件还是函数式组件都可以。逻辑是相同的。 - FreakyCoder
是的,这是由于 info.plist 文件。我添加了所需的代码并且它可以工作。 - masterAvatarr

0
我建议安装这个库:https://www.npmjs.com/package/expo-screen-orientation
使用以下命令进行安装。
npm install expo-screen-orientation

然后在你的主入口文件(可以是app.js或index.js)上。
import * as ScreenOrientation from "expo-screen-orientation";

然后执行以下步骤以锁定横向方向。

export default function App() {

  //Locking Orientation
  const [orientation, setOrientation] = useState(1);
  useEffect(() => {
    lockOrientation();
  }, []);
  const lockOrientation = async () => {
    await ScreenOrientation.lockAsync(
      ScreenOrientation.OrientationLock.LANDSCAPE_RIGHT
    );
    const o = await ScreenOrientation.getOrientationAsync();
    setOrientation(o);
  };
//REST OF THE CODE
  return (
    <Components></Components>
  );
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接