How to change UIWebView orientation programmatical

2020-04-19 07:52发布

问题:

I've created UIWebView programmatically. Now i want to set programmatically its orientation to (landscape or portrait). Please can anyone tell me how i can do this? Thanks

import UIKit
class ViewController: UIViewController, UIWebViewDelegate  {

    override func viewDidLoad() {
        super.viewDidLoad()

        let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
        webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://tune.tv/humtv-live-embed")!))
        webV.delegate = self;
        self.view.addSubview(webV)
    }
 }

回答1:

In your viewDidAppear add the following:

override func viewDidAppear(animated: Bool) {
    let value = UIInterfaceOrientation.LandscapeRight.rawValue
    UIDevice.currentDevice().setValue(value, forKey: "orientation")
}

Swift 3.0:

override func viewDidAppear(_ animated: Bool) {
    let value = UIInterfaceOrientation.landscapeRight.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}

Just choose your orientation and it will be set to it when the WebView is shown.