uni app 按钮控制 横屏展示

uni app 按钮控制 横屏展示
 

在 Uni App 中实现按钮控制横屏展示,主要有两种方案,具体取决于你的需求:

  1. 强制横屏:点击按钮后,页面强制旋转为横屏(推荐用于视频播放、游戏等场景)。

  2. 跟随系统:点击按钮后,允许设备根据重力感应自动旋转。

以下是具体的实现代码和配置步骤。


方案一:强制横屏(最常用)

这种方式下,点击按钮会直接锁定为横屏(landscape),再次点击可恢复为竖屏(portrait)。

1. 核心代码实现

直接在页面的 <script> 中调用 uni.setScreenOrientation 接口。

html
<template>
  <view class="content">
    <button type="primary" @click="toggleScreen">
      {{ isLandscape ? '切换竖屏' : '切换横屏' }}
    </button>
    <text>当前状态: {{ isLandscape ? '横屏' : '竖屏' }}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isLandscape: false
    };
  },
  methods: {
    toggleScreen() {
      this.isLandscape = !this.isLandscape;
      if (this.isLandscape) {
        // 强制横屏(注意:方向参数需根据实际需求选择)
        uni.setScreenOrientation({
          orientation: 'landscape-primary', // 或 'landscape-secondary'
          success: () => {
            console.log('切换横屏成功');
          },
          fail: (err) => {
            console.error('切换失败', err);
            // 如果失败,回滚状态
            this.isLandscape = false;
            uni.showToast({ title: '横屏切换失败', icon: 'none' });
          }
        });
      } else {
        uni.setScreenOrientation({
          orientation: 'portrait-primary', // 竖屏
          success: () => {
            console.log('切换竖屏成功');
          }
        });
      }
    }
  }
};
</script>

2. 方向参数说明(重要)

  • portrait-primary:正向竖屏(Home 键在下)。

  • portrait-secondary:反向竖屏(Home 键在上,部分手机支持)。

  • landscape-primary:正向横屏(Home 键在右)。

  • landscape-secondary:反向横屏(Home 键在左)。


方案二:切换“重力感应”模式

如果你希望点击按钮后,手机可以根据握持方向自动旋转(而不是锁死方向),可以传入 orientation: 'auto'

javascript
// 点击按钮允许自动旋转
uni.setScreenOrientation({
  orientation: 'auto',
  success() {
    console.log('已开启重力感应,请旋转手机');
  }
});

必填配置(App 端 Android 注意)

如果你打包的是 App,且使用 Android 系统,必须在 manifest.json 中配置屏幕方向,否则 setScreenOrientation 可能不生效。

操作步骤:

  1. 打开项目根目录的 manifest.json

  2. 选择 App 启动界面配置

  3. 找到 屏幕方向,勾选所有你需要的方向(必须勾选“竖屏”和“横屏”,否则无法切换)。

https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/screen-orientation.png


注意事项(避坑指南)

 
平台注意事项
App (Android) 必须配置 manifest.json 中的屏幕方向,否则调用 setScreenOrientation 会失败。
App (iOS) 除了配置 manifest,还需在 Xcode 中勾选横屏支持,但一般云打包默认支持。
H5 端 浏览器限制,setScreenOrientation 在手机上可能不支持,建议使用 CSS transform 旋转或 screen.orientation.lock()(需用户手势触发)。
小程序 微信小程序支持 wx.setScreenOrientation,但需要小程序基础库版本支持,且需在 app.json 中配置 "resizable": true

升级技巧:监听横竖屏变化

如果你想在页面显示时根据横竖屏调整 UI,可以监听窗口变化:

javascript
// 在 onLoad 或 mounted 中监听
uni.onWindowResize((res) => {
  // res.size.windowWidth 和 res.size.windowHeight
  if (res.size.windowWidth > res.size.windowHeight) {
    console.log('当前是横屏');
  } else {
    console.log('当前是竖屏');
  }
});

如果你需要完整的视频播放器横屏代码示例,或者遇到 H5端无法横屏 的兼容性问题,可以告诉我,我再针对你的平台给你写详细的解决方案。😊

 
22:00:17.971 [JS Framework] Failed to execute the callback function: TypeError: uni.setScreenOrientation is not a function 22:00:17.986 reportJSException >>>> exception function:__WEEX_CALL_JAVASCRIPT__, exception:JavaScript execute error!Uncaught TypeError: uni.setScreenOrientation is not a function at scanMatchDish (app-service.js:89234:13) at handleSearch (app-service.js:89254:9) at (app-service.js:89192:17)
 

这个错误说明 uni.setScreenOrientation 在你当前的环境下不可用。根据报错堆栈中的 __WEEX_CALL_JAVASCRIPT__ 和 app-service.js,可以确定你运行在 微信小程序 环境下。

问题原因

微信小程序的屏幕方向 API 是 wx.setScreenOrientation,而不是 uni.setScreenOrientation。Uni App 虽然封装了跨平台 API,但在某些小程序版本或基础库下,可能没有正确映射。

解决方案

方案一:使用条件编译(推荐)

针对不同平台调用不同的 API,这是 Uni App 的标准做法。

html
<template>
  <view class="content">
    <button type="primary" @click="toggleScreen">
      {{ isLandscape ? '切换竖屏' : '切换横屏' }}
    </button>
    <text>当前状态: {{ isLandscape ? '横屏' : '竖屏' }}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isLandscape: false
    };
  },
  methods: {
    toggleScreen() {
      this.isLandscape = !this.isLandscape;
      
      // #ifdef MP-WEIXIN
      // 微信小程序专用
      wx.setScreenOrientation({
        orientation: this.isLandscape ? 'landscape' : 'portrait',
        success: () => {
          console.log('切换成功');
        },
        fail: (err) => {
          console.error('切换失败', err);
          this.isLandscape = !this.isLandscape; // 回滚状态
          uni.showToast({ title: '切换失败,请检查配置', icon: 'none' });
        }
      });
      // #endif
      
      // #ifdef APP-PLUS || H5
      // App 和 H5 使用 uni 的 API
      uni.setScreenOrientation({
        orientation: this.isLandscape ? 'landscape-primary' : 'portrait-primary',
        success: () => {
          console.log('切换成功');
        },
        fail: (err) => {
          console.error('切换失败', err);
          this.isLandscape = !this.isLandscape;
        }
      });
      // #endif
    }
  }
};
</script>

方案二:统一封装(更优雅)

创建一个工具函数,自动判断环境:

javascript
// utils/screen.js
export function setScreenOrientation(orientation) {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    wx.setScreenOrientation({
      orientation: orientation,
      success: resolve,
      fail: reject
    });
    // #endif
    
    // #ifdef APP-PLUS || H5
    uni.setScreenOrientation({
      orientation: orientation,
      success: resolve,
      fail: reject
    });
    // #endif
  });
}

// 使用示例
import { setScreenOrientation } from '@/utils/screen.js';

// 切换横屏
setScreenOrientation('landscape')
  .then(() => console.log('成功'))
  .catch(err => console.error('失败', err));

微信小程序额外配置(必须)

1. 在 app.json 中开启屏幕旋转支持

在项目根目录的 manifest.json → mp-weixin 配置中,添加:

json
{
  "mp-weixin": {
    "appid": "你的AppID",
    "setting": {
      "urlCheck": false
    },
    "resizable": true  // ← 关键配置,允许屏幕旋转
  }
}

2. 页面单独配置(可选)

如果需要某个页面支持横屏,在该页面的 json 文件中:

json
{
  "navigationBarTitleText": "页面标题",
  "pageOrientation": "auto"  // 可选值: auto, portrait, landscape
}

3. 微信小程序基础库版本要求

  • 需要基础库版本 2.4.0 以上

  • 在微信开发者工具中检查:详情 → 本地设置 → 调试基础库


完整可运行示例(微信小程序专用)

html
<template>
  <view class="container">
    <view class="status">当前:{{ isLandscape ? '🌐 横屏' : '📱 竖屏' }}</view>
    
    <button class="btn" @click="toggleScreen">
      {{ isLandscape ? '切换到竖屏' : '切换到横屏' }}
    </button>
    
    <view class="tip">提示:请确保 manifest.json 中已配置 resizable: true</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isLandscape: false
    };
  },
  methods: {
    toggleScreen() {
      const target = !this.isLandscape;
      
      // #ifdef MP-WEIXIN
      wx.setScreenOrientation({
        orientation: target ? 'landscape' : 'portrait',
        success: () => {
          this.isLandscape = target;
          uni.showToast({ 
            title: target ? '已切换横屏' : '已切换竖屏',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('切换失败:', err);
          uni.showToast({ 
            title: '切换失败,请检查配置', 
            icon: 'none' 
          });
        }
      });
      // #endif
    }
  }
};
</script>

<style>
.container {
  padding: 40rpx;
  text-align: center;
}
.status {
  font-size: 36rpx;
  margin: 60rpx 0;
}
.btn {
  margin: 40rpx auto;
  width: 400rpx;
}
.tip {
  color: #999;
  font-size: 24rpx;
  margin-top: 80rpx;
}
</style>

常见失败原因排查

 
问题解决方案
wx.setScreenOrientation is not a function 基础库版本过低,升级到 2.4.0+
调用成功但屏幕不旋转 manifest.json 中未配置 "resizable": true
真机调试失败 在微信公众平台 → 开发设置 → 服务器域名中添加合法域名(如果有网络请求)
部分安卓手机无效 微信版本过低,更新微信到最新版

调试建议

  1. 在微信开发者工具中:点击「编译」→「详情」→「本地设置」→ 勾选「不校验合法域名」便于调试

  2. 真机预览:使用微信扫码预览,横屏效果在模拟器上可能不准确

  3. 查看日志:在 fail 回调中打印 err 详细信息

posted @ 2026-07-03 09:36  张筱菓  阅读(49)  评论(0)    收藏  举报