奔五的人学iOS:swift对 状态栏、导航条若干技巧

1、状态栏反色

a.在info中添加 View controller-based status bar appearance,并将值设置 NO,表明不由系统控制,由vc自己控制;

b.在viewWillApear中使用以下代码实现反色

UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
//UIApplication.shared.statusBarStyle = .lightContent

c.在viewWillDisapper中使用以下代码实现恢复

UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true)
//UIApplication.shared.statusBarStyle = .default

两句效果一样,只是一种有动态效果,另外有人说override preferredStatusBarStyle,本人试了,不管用。


2、导航条透明以及文字颜色、其他按钮颜色

        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
        self.navigationController?.navigationBar.tintColor = UIColor.white

以上代码在viewWillApear中,以下代码在viewWillDisappear中进行恢复

        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black]
        self.navigationController?.navigationBar.tintColor = UIColor.black

透明只对当前有效,返回上一级后不影响,文字颜色及控件颜色对上一级有影响,所以需要恢复


3、锁定屏幕方向

a.在AppDelegate中实现

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if !self.blockRotation {
            return UIInterfaceOrientationMask.all
        } else {
            return UIInterfaceOrientationMask.portrait
        }
    }

    var blockRotation: Bool = false

b.扩展UIViewController

extension UIViewController {
    var app : AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

c.在需要锁定屏幕的地方,一般是viewWillApear中

        app.blockRotation = true
        old = UIDevice.current.value(forKey: "orientation")
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")

d.退出时恢复状态

app.blockRotation = false

我这里是锁定为竖屏,其他值可根据你自己的情况选择


以上整理内容在xcode 8.2.1(8C1002)中,用swift3实现,希望对各位有帮助,不用东奔西跑了。

猜你喜欢

转载自blog.csdn.net/miw__/article/details/55668925