允许一个控制器能够旋转到横向模式

时间:2017-12-02 06:21:17

标签: ios swift

好的所以我有一个视图控制器,它是一个AVPlayer。我希望该控制器能够自由旋转到横向模式和肖像

import Foundation
import UIKit
import AVFoundation
import AVKit

class EventPromoVideoPlayer: UIViewController {
    public var eventKey = ""

    override var prefersStatusBarHidden: Bool {
        return true
    }
    //URL of promo video that is about to be played
    private var videoURL: URL
    // Allows you to play the actual mp4 or video
    var player: AVPlayer?
    // Allows you to display the video content of a AVPlayer
    var playerController : AVPlayerViewController?

    init(videoURL: URL) {
        self.videoURL = videoURL
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.gray
        let downSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(_:)))
        downSwipe.direction = .down
        view.addGestureRecognizer(downSwipe)


        //Setting the video url of the AVPlayer
        player = AVPlayer(url: videoURL)
        playerController = AVPlayerViewController()

        guard player != nil && playerController != nil else {
            return
        }
        playerController!.showsPlaybackControls = false
        // Setting AVPlayer to the player property of AVPlayerViewController
        playerController!.player = player!
        self.addChildViewController(playerController!)
        self.view.addSubview(playerController!.view)
        playerController!.view.frame = view.frame
        // Added an observer for when the video stops playing so it can be on a continuous loop
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player!.currentItem)
        //TODO: Need to fix frame of x and y
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        player?.play()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isHidden = true
        tabBarController?.tabBar.isHidden = true
    }

    override var supportedInterfaceOrientations:UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.all
    }
    // Allows the video to keep playing on a loop
    @objc fileprivate func playerItemDidReachEnd(_ notification: Notification) {
        if self.player != nil {
            self.player!.seek(to: kCMTimeZero)
            self.player!.play()
        }
    }

    @objc func cancel() {
        dismiss(animated: true, completion: nil)
    }

    @objc func swipeAction(_ swipe: UIGestureRecognizer){
        if let swipeGesture = swipe as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.right:
                print("Swiped right")
                break
            case UISwipeGestureRecognizerDirection.down:
                print("Swiped Down")
                dismiss(animated: true, completion: nil)
                break
            case UISwipeGestureRecognizerDirection.left:
                print("Swiped left")
                break
            case UISwipeGestureRecognizerDirection.up:
                print("Swiped up")
                break
            default:
                break
            }
        }
    }
}

当我关闭屏幕时,我仍然需要先前的控制器处于纵向状态。这不应该是一个问题,因为纵向模式被锁定为我设置中的唯一方向,我想保持这种方式。但是我希望这个屏幕能够自由移动。任何想法和提示将不胜感激。

app delegate方法对我不起作用。 在函数

中覆盖shouldAutoRotate或supportedInterfaceOrientations也没有

1 个答案:

答案 0 :(得分:0)

您可以在app delegate中使用以下方法。

<!DOCTYPE html>
<html>
<head>
    <meta content="text/html" charset="utf-8" http-equiv="content-type" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Index - Plataforma Fantasy Park</title>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="/js/jquery.dataTables.min.js?v=qcV1wr-bn4NoBtxYqghmy1WIBvxeoe8vQlCowLG-cng"></script>
        <script src="/js/dataTables.bootstrap.min.js?v=X_58s5WblGMAw9SpDtqnV8dLRNCawsyGwNqnZD0Je_s"></script>
        <script src="/js/site.js?v=ViqmmChOp_51fH3dM_KEQAFClKU0vp0UrxlREwyHKHc"></script>

        <link rel="stylesheet" href="/css/bootstrap-lumen.css" />
        <link rel="stylesheet" href="/css/site.css" />
        <link rel="stylesheet" href="/css/nestednavbar.css" />
        <link rel="stylesheet" href="/css/dataTables.bootstrap.min.css" />    

</head>
<body>

    <div class="container body-content">


<nav class="navbar navbar-inverse navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Menu</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Plataforma Fantasy Park</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                                    <li><a href="/HechosLiquidadors/IndexAdmin">Liquidaciones</a></li>
                                <li>
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button">Máquinas <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li class="dropdown-submenu">
                            <a href="#" class="dropdown-item" tabindex="-1">Registro</a>
                            <ul class="dropdown-menu">
                                <li class="dropdown-item"><a tabindex="-1" href="/Machines">Datos Comerciales</a></li>
                                <li class="dropdown-item"><a tabindex="-1" href="/Machines/Workshop">Datos de Fabricación</a></li>
                            </ul>
                        </li>
                        <li class="divider"></li>
                        <li><a href="/Machines/Familias">Familias y Tipos</a></li>
                        <li class="dropdown-submenu">
                            <a href="#" class="dropdown-item" tabindex="-1">Gestión</a>
                            <ul class="dropdown-menu">
                                <li class="dropdown-item"><a tabindex="-1" href="/Machines/Management">Máquinas</a></li>
                                <li class="dropdown-item"><a tabindex="-1" href="/Machines/Contadores">Contadores</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                                <li>
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button">Tiendas <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="/Stores">Registro</a></li>
                        <li class="divider"></li>
                        <li><a href="/Stores/Management">Liquidadores</a></li>
                    </ul>
                </li>
                                <li>
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button">Proveedores <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="/Suppliers/Supplier">Fabricantes y Marcas</a></li>
                        <li><a href="/Suppliers/Dealer">Dealers</a></li>
                    </ul>
                </li>
                                <li><a href="/">Gastos</a></li>
                                <li>
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button">Usuarios <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="/User">Usuarios</a></li>
                        <li><a href="/ApplicationRole">Roles</a></li>
                    </ul>
                </li>
                <li><a href="/Home/About">About</a></li>
            </ul>


    <form method="post" id="logoutForm" class="navbar-right" action="/Account/SignOff">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a title="Manage" href="/Manage">Hello adelgado!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
            </li>
        </ul>
    <input name="__RequestVerificationToken" type="hidden" value="CfDJ8P12Ot7bDOBImhnZFhlI8qHJtKdMI-7lr8LhbUsd_y-3eQSYnYA19_MyhKx_JGsHcwdpm_ZQCqHibSVsLLwXaJ-PRiZg6VJXvFUtHaAK6IAPSBfOgrVrEBeimgbOvB60ahTqLMUeuUsFEXIIrmYiyBgxQVeQJEkPBbIEsMlFv-8A91-ULjKZlim2P0NZaUuLSA" /></form>

            </div>
        </div>
</nav>




<h2>Tiendas</h2>

<div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" data-target="#modal-action-store" class="btn btn-primary" href="/Stores/Create">
            <i class="glyphicon glyphicon-plus"></i>  Nueva Tienda
        </a>
</div>
<p></p>
<table id="stores" class="table table-bordered table-hover table-striped">
    <thead>
        <tr>
            <th>
                Tienda
            </th>
            <th>
                Dirección
            </th>
            <th>
                Área
            </th>
            <th>
                Distrito
            </th>
            <th>
                Cadena
            </th>
            <th>Editar</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>


<div aria-hidden="true" aria-labelledby="modal-action-store-label" role="dialog" tabindex="-1" id="modal-action-store" class="modal fade">
    <div class="modal-dialog ">
        <div class="modal-content">
        </div>
    </div>
</div>


        <hr />
        <footer>
            <p>&copy; 2017 - Plataforma Fantasy Park</p>
        </footer>
    </div>


<script src="/js/store-index.js?v=xMseET7-q434oUXfBjpd5QKjSw8t0R0P_mGdZorHwB0"></script>
<script type="text/javascript">

    var global = this;
    var wasclicked = 0;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            global.wasclicked = 1;
        };

        $('#modal-action-store').on('hidden.bs.modal', function () {
            global.wasclicked = 0;
        });

        $('#modal-action-store').on('shown.bs.modal', function () {
            if (global.wasclicked == 1) {
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            }
            $('#DepartmentID').change(function () {
                var url = '/' + "Stores/GetDistrict";
                var ddlsource = "#DepartmentID";
                $.getJSON(url, { DepartmentID: $(ddlsource).val() }, function (data) {
                    var items = '';
                    $("#DistrictID").empty();
                    $.each(data, function (i, district) {
                        items += "<option value='" + district.value + "'>" + district.text + "</option>";
                    });
                    $('#DistrictID').html(items);
                });
            });
        });
    });
</script>


</body>
</html> 

在视图控制器中添加以下方法,将其显示为横向。

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if let rootViewController = UIApplication.topViewController() {
        if (rootViewController.responds(to: Selector(("canRotate")))) || String(describing: type(of: rootViewController)) == "AVFullScreenViewController" {
            // Unlock landscape view orientations for this view controller
            return .allButUpsideDown;
        }
    }
    // Only allow portrait (standard behaviour)
    return .portrait
}