Programing

Swift에서 탐색 막대 색상 변경

lottogame 2020. 4. 27. 07:53
반응형

Swift에서 탐색 막대 색상 변경


사용자가 전체 앱의 색상 테마를 선택할 수 있도록 선택기보기를 사용하고 있습니다. 탐색 표시 줄, 배경 및 탭 표시 줄의 색상을 변경하려고합니다 (가능한 경우). 이 작업을 수행하는 방법을 연구했지만 Swift 예제를 찾을 수 없습니다. 네비게이션 바 색상과 네비게이션 바 텍스트 색상을 변경하는 데 사용해야하는 코드의 예를 알려주시겠습니까? (피커보기가 설정되었습니다 .UI 색상을 변경하는 코드를 찾고 있습니다)

감사.


네비게이션 바 :

navigationController?.navigationBar.barTintColor = UIColor.green

greenColor를 원하는 UIColor로 바꾸십시오. 원한다면 RGB도 사용할 수 있습니다.

탐색 줄 텍스트 :

navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]

orangeColor를 원하는 색상으로 바꾸십시오.

탭 바 :

tabBarController?.tabBar.barTintColor = UIColor.brown

탭 바 텍스트 :

tabBarController?.tabBar.tintColor = UIColor.yellow

마지막 두 가지에서 brownColor와 yellowColor를 선택한 색상으로 바꿉니다.


다음은 앱 전체에 적용 할 수있는 매우 기본적인 모양 사용자 지정입니다.

UINavigationBar.appearance().backgroundColor = UIColor.greenColor()
UIBarButtonItem.appearance().tintColor = UIColor.magentaColor()
//Since iOS 7.0 UITextAttributeTextColor was replaced by NSForegroundColorAttributeName
UINavigationBar.appearance().titleTextAttributes = [UITextAttributeTextColor: UIColor.blueColor()]
UITabBar.appearance().backgroundColor = UIColor.yellowColor();

UIAppearanceSwift의 API에 대한 자세한 내용은 https://developer.apple.com/documentation/uikit/uiappearance를 참조 하십시오.


    UINavigationBar.appearance().barTintColor = UIColor(red: 46.0/255.0, green: 14.0/255.0, blue: 74.0/255.0, alpha: 1.0)
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

이 줄을 didFinishLaunchingWithOptions코드 에 붙여 넣으 십시오.


스위프트 3, 4 및 4.2 용으로 업데이트

// setup navBar.....
UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
UINavigationBar.appearance().isTranslucent = false

스위프트 4

UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false

스위프트 4.2

UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false

또한 여기에서 확인할 수 있습니다 : https://github.com/hasnine/iOSUtilitiesSource


AppDelegate에서 이것은 NavBar의 형식을 전 세계적으로 변경했으며 대부분의 사람들에게 문제가되는 결론 / 경계선을 제거하여 귀하와 다른 사람들이 찾고 있다고 생각하는 것을 제공합니다.

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
    UINavigationBar.appearance().barTintColor = Style.SELECTED_COLOR
    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().clipsToBounds = false
    UINavigationBar.appearance().backgroundColor = Style.SELECTED_COLOR
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : (UIFont(name: "FONT NAME", size: 18))!, NSForegroundColorAttributeName: UIColor.whiteColor()] }

그런 다음 Constants.swift 파일을 설정할 수 있으며 색상 및 글꼴 등이 포함 된 Style 구조체가 포함되어 있습니다. 그런 다음 tableView / pickerView를 모든 ViewController에 추가하고 "availableThemes"배열을 사용하여 themeColor를 변경할 수 있습니다.

이것에 대한 아름다운 점은 각 색상에 대해 전체 앱에서 하나의 참조를 사용할 수 있으며 사용자가 선택한 "테마"에 따라 업데이트되며 기본적으로 theme1 ()입니다.

import Foundation
import UIKit

struct Style {


static let availableThemes = ["Theme 1","Theme 2","Theme 3"]

static func loadTheme(){
    let defaults = NSUserDefaults.standardUserDefaults()
    if let name = defaults.stringForKey("Theme"){
        // Select the Theme
        if name == availableThemes[0]   { theme1()  }
        if name == availableThemes[1]   { theme2()  }
        if name == availableThemes[2]   { theme3()  }
    }else{
        defaults.setObject(availableThemes[0], forKey: "Theme")
        theme1()
    }
}

 // Colors specific to theme - can include multiple colours here for each one
static func theme1(){
   static var SELECTED_COLOR = UIColor(red:70/255, green: 38/255, blue: 92/255, alpha: 1) }

static func theme2(){
    static var SELECTED_COLOR = UIColor(red:255/255, green: 255/255, blue: 255/255, alpha: 1) }

static func theme3(){
    static var SELECTED_COLOR = UIColor(red:90/255, green: 50/255, blue: 120/255, alpha: 1) } ...

스토리 보드에서이를 수행하려면 (인터페이스 빌더 관리자)

의 도움으로 IBDesignableInterface Builder Inspector에 더 많은 옵션을 추가 UINavigationController하고 스토리 보드에서 조정할 수 있습니다. 먼저 다음 코드를 프로젝트에 추가하십시오.

@IBDesignable extension UINavigationController {
    @IBInspectable var barTintColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            navigationBar.barTintColor = uiColor
        }
        get {
            guard let color = navigationBar.barTintColor else { return nil }
            return color
        }
    }
}

그런 다음 스토리 보드에서 탐색 컨트롤러의 속성을 설정하십시오.

여기에 이미지 설명을 입력하십시오

이 방법은 스토리 보드에서 탐색 막대 텍스트의 색상을 관리하는 데 사용될 수도 있습니다.

@IBInspectable var barTextColor: UIColor? {
  set {
    guard let uiColor = newValue else {return}
    navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: uiColor]
  }
  get {
    guard let textAttributes = navigationBar.titleTextAttributes else { return nil }
    return textAttributes[NSAttributedStringKey.foregroundColor] as? UIColor
  }
}

UINavigationBar.appearance().barTintColor

나를 위해 일했다


스위프트 4 :

응용 프로그램 수준에서 탐색 모음 모양을 변경하는 완벽하게 작동하는 코드입니다.

여기에 이미지 설명을 입력하십시오

// MARK: Navigation Bar Customisation

// To change background colour.
UINavigationBar.appearance().barTintColor = .init(red: 23.0/255, green: 197.0/255, blue: 157.0/255, alpha: 1.0)

// To change colour of tappable items.
UINavigationBar.appearance().tintColor = .white

// To apply textAttributes to title i.e. colour, font etc.
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : UIColor.white,
                                                    .font : UIFont.init(name: "AvenirNext-DemiBold", size: 22.0)!]
// To control navigation bar's translucency.
UINavigationBar.appearance().isTranslucent = false

행복한 코딩!


SWIFT 4-원활한 전환 (최상의 솔루션) :

내비게이션 컨트롤러에서 뒤로 이동하는 경우 사용하려는 내비게이션 컨트롤러에서 다른 색상을 설정해야하는 경우

override func willMove(toParentViewController parent: UIViewController?) {
    navigationController?.navigationBar.barTintColor = .white
    navigationController?.navigationBar.tintColor = Constants.AppColor
}

viewWillAppear에 배치하는 대신 전환이 더 깨끗합니다.

스위프트 4.2

override func willMove(toParent parent: UIViewController?) {
    navigationController?.navigationBar.barTintColor = UIColor.black
    navigationController?.navigationBar.tintColor = UIColor.black
}

에서 스위프트 4

탐색 막대의 색상을 변경할 수 있습니다. 아래의 코드 스 니펫을 사용하십시오.viewDidLoad()

네비게이션 바 색상

self.navigationController?.navigationBar.barTintColor = UIColor.white

탐색 막대 텍스트 색상

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]

들어 아이폰 OS (11) 큰 제목 탐색 막대 , 당신은 사용할 필요가 largeTitleTextAttributes속성을

self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]

모양 API와 barTintColor 색상을 사용하십시오.

UINavigationBar.appearance().barTintColor = UIColor.greenColor()

The appearance() function not always work for me. So I prefer to create a NC object and change its attributes.

var navBarColor = navigationController!.navigationBar
        navBarColor.barTintColor = UIColor(red:  255/255.0, green: 0/255.0, blue: 0/255.0, alpha: 100.0/100.0)
        navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]

Also if you want to add an image instead of just text, that works as well

var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
        imageView.contentMode = .ScaleAspectFit

        var image = UIImage(named: "logo")
        imageView.image = image
        navigationItem.titleView = imageView

iOS 8 (swift)

let font: UIFont = UIFont(name: "fontName", size: 17)   
let color = UIColor.backColor()
self.navigationController?.navigationBar.topItem?.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName: color], forState: .Normal)

If you have customized navigation controller, you can use above code snippet. So in my case, I've used as following code pieces.

Swift 3.0, XCode 8.1 version

navigationController.navigationBar.barTintColor = UIColor.green

Navigation Bar Text:

navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]

It is very helpful talks.


Swift 4, iOS 12 and Xcode 10 Update

Just put one line inside viewDidLoad()

navigationController?.navigationBar.barTintColor = UIColor.red

In Swift 2

For changing color in navigation bar,

navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

For changing color in item navigation bar,

navigationController?.navigationBar.tintColor = UIColor.blueColor()

or

navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blueColor()]

Swift 3

UINavigationBar.appearance().barTintColor = UIColor(colorLiteralRed: 51/255, green: 90/255, blue: 149/255, alpha: 1)

This will set your navigation bar color like Facebook bar color :)


Swift 3 and Swift 4 Compatible Xcode 9

A Better Solution for this to make a Class for common Navigation bars

I have 5 Controllers and each controller title is changed to orange color. As each controller has 5 navigation controllers so i had to change every one color either from inspector or from code.

So i made a class instead of changing every one Navigation bar from code i just assign this class and it worked on all 5 controller Code reuse Ability. You just have to assign this class to Each controller and thats it.

import UIKit

   class NabigationBar: UINavigationBar {
      required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    commonFeatures()
 }

   func commonFeatures() {

    self.backgroundColor = UIColor.white;
      UINavigationBar.appearance().titleTextAttributes =     [NSAttributedStringKey.foregroundColor:ColorConstants.orangeTextColor]

 }


  }

iOS 10 Swift 3.0

If you don't mind to use swift frameworks then us UINeraida to change navigation background as UIColor or HexColor or UIImage and change navigation back button text programmatically, change complete forground text color.

For UINavigationBar

    neraida.navigation.background.color.hexColor("54ad00", isTranslucent: false, viewController: self)

    //Change navigation title, backbutton colour

    neraida.navigation.foreground.color.uiColor(UIColor.white, viewController: self)

    //Change navigation back button title programmatically

    neraida.navigation.foreground.backButtonTitle("Custom Title", ViewController: self)

    //Apply Background Image to the UINavigationBar

    neraida.navigation.background.image("background", edge: (0,0,0,0), barMetrics: .default, isTranslucent: false, viewController: self)

Swift 3

Simple one liner that you can use in ViewDidLoad()

//Change Color
    self.navigationController?.navigationBar.barTintColor = UIColor.red
//Change Text Color
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

I had to do

UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().barStyle = .Black
UINavigationBar.appearance().backgroundColor = UIColor.blueColor()

otherwise the background color wouldn't change


먼저 navigationBar의 isTranslucent 속성을 false로 설정하여 원하는 색상을 얻으십시오. 그런 다음 navigationBar 색상을 다음과 같이 변경하십시오.

@IBOutlet var NavigationBar: UINavigationBar!

NavigationBar.isTranslucent = false
NavigationBar.barTintColor = UIColor (red: 117/255, green: 23/255, blue: 49/255, alpha: 1.0)

버튼 상태를 .normal 로 설정하십시오.

extension UINavigationBar {

    func makeContent(color: UIColor) {
        let attributes: [NSAttributedString.Key: Any]? = [.foregroundColor: color]

        self.titleTextAttributes = attributes
        self.topItem?.leftBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
        self.topItem?.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
    }
}

PS iOS 12, Xcode 10.1


AppDelegate에서 이것을 시도하십시오 :

//MARK:- ~~~~~~~~~~setupApplicationUIAppearance Method
func setupApplicationUIAppearance() {

    UIApplication.shared.statusBarView?.backgroundColor = UIColor.clear

    var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    UINavigationBar.appearance().tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    UINavigationBar.appearance().barTintColor =  UIColor.white
    UINavigationBar.appearance().isTranslucent = false

    let attributes: [NSAttributedString.Key: AnyObject]

    if DeviceType.IS_IPAD{
        attributes = [
            NSAttributedString.Key.foregroundColor: UIColor.white,
            NSAttributedString.Key.font: UIFont(name: "HelveticaNeue", size: 30)
            ] as [NSAttributedString.Key : AnyObject]
    }else{
        attributes = [
            NSAttributedString.Key.foregroundColor: UIColor.white
        ]
    }
    UINavigationBar.appearance().titleTextAttributes = attributes
}

참고 URL : https://stackoverflow.com/questions/24687238/changing-navigation-bar-color-in-swift

반응형