Check Landscape/Portrait orientation in an iMessage app (extension)

ε祈祈猫儿з 提交于 2019-12-31 05:23:10

问题


Have seen a lot of solutions to check the orientation, but strangely, none works!!

Below is the code snippet,

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    let screenSize = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height

    print("Screen Width = \(screenWidth)")
    print("Screen Height = \(screenHeight)")

    if (screenWidth > screenHeight) {
        print("Landscape")
        alertView.removeFromSuperview()
        messageView.addGestureRecognizer(tapTextView)
    }
    else {
        print("Portrait")
        setupLandscapeAlertView()
    }
}

The other method which is used to setup the view is,

fileprivate func setupLandscapeAlertView() {
    messageView.removeGestureRecognizer(tapTextView)

    alertView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
    alertView.backgroundColor = UIColor.clear
    alertView.isUserInteractionEnabled = false

    let transparentView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.height, height: self.view.frame.width))
    transparentView.backgroundColor = UIColor.gray
    transparentView.backgroundColor = transparentView.backgroundColor!.withAlphaComponent(0.6)
    transparentView.isUserInteractionEnabled = false
    alertView.addSubview(transparentView)

    let blurEffect = UIBlurEffect(style: .regular)
    let blurredEffectView = UIVisualEffectView(effect: blurEffect)
    blurredEffectView.frame = transparentView.bounds
    blurredEffectView.isUserInteractionEnabled = false
    alertView.addSubview(blurredEffectView)

    let imageView = UIImageView(image: UIImage(named: "LandscapeAlert"))
    imageView.frame = CGRect(x: 70, y: 75, width: imageView.frame.width, height: imageView.frame.height)
    imageView.contentMode = UIViewContentMode.scaleAspectFit
    imageView.contentMode = UIViewContentMode.center
    imageView.isUserInteractionEnabled = false
    alertView.addSubview(imageView)

    self.view.addSubview(alertView)
}

Another thing is that, this image isn't centered. How do I go about that? Again, too many solutions, but nothing does the job.

Not sure if I'm doing anything wrong. :-/


回答1:


This may be because viewWillTransition executes before the view actually flips. If you do a simple print("height width \(view.frame.height) \(view.frame.width)") inside the viewWillTransition block you will see.



来源:https://stackoverflow.com/questions/44632424/check-landscape-portrait-orientation-in-an-imessage-app-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!