ZAFAR007 ZAFAR007 - 1 month ago 16
Swift Question

How to change UIWebView orientation programmatically in Swift

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)
}
}

Answer

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.

Comments