Animating a navigation bar color

两盒软妹~` 提交于 2019-11-29 12:20:32

Details

xCode 8.3.2, swift 3.1

Solution

override func viewWillAppear(_ animated: Bool) {
    if let navigationBar = self.navigationController?.navigationBar {
        navigationBar.backgroundColor = .blue
    }
}

Full sample

ViewController

import UIKit

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.barTintColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1.0)
            navigationBar.tintColor = .white
            navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
            navigationBar.isTranslucent = false
        }
    }
}

ViewController2

import UIKit

class ViewController2: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            let color = UIColor(red: 1, green: 153/255, blue: 0, alpha: 1.0)
            navigationBar.setBackgroundImage(UIImage.imageWithColor(color: color), for: .default)
            navigationBar.shadowImage = UIImage()
            navigationBar.isTranslucent = true
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.setBackgroundImage(nil, for: .default)
            navigationBar.shadowImage = nil
            navigationBar.isTranslucent = false
        }
    }
}

extension UIImage

import UIKit

extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

Main.storyboard

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="Tzy-ol-uu0">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackowerflow_44343355" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="eIC-Nm-Ex7">
                                <rect key="frame" x="164" y="318" width="46" height="30"/>
                                <state key="normal" title="Button"/>
                                <connections>
                                    <segue destination="QHs-H4-fAS" kind="show" id="Rff-Eq-K6g"/>
                                </connections>
                            </button>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="eIC-Nm-Ex7" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="G1g-VM-MAn"/>
                            <constraint firstItem="eIC-Nm-Ex7" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="mdZ-GP-EQw"/>
                        </constraints>
                    </view>
                    <navigationItem key="navigationItem" id="hq3-zt-U4K"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="977" y="791"/>
        </scene>
        <!--View Controller2-->
        <scene sceneID="F9C-Nz-6dd">
            <objects>
                <viewController id="QHs-H4-fAS" customClass="ViewController2" customModule="stackowerflow_44343355" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="AV0-X8-nhX"/>
                        <viewControllerLayoutGuide type="bottom" id="AsY-Gl-67v"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="1fA-pX-rzR">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="Uzd-Tb-KRO" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="1770" y="789"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="Jff-OO-3e7">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="Tzy-ol-uu0" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" id="804-YF-T6T">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="BRB-ym-7I2"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="M6i-ib-61I" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="140" y="791.15442278860576"/>
        </scene>
    </scenes>
</document>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!