development

탭 바에서 비활성 아이콘 / 텍스트 색상을 변경하는 방법은 무엇입니까?

big-blog 2020. 12. 13. 10:08
반응형

탭 바에서 비활성 아이콘 / 텍스트 색상을 변경하는 방법은 무엇입니까?


iOS 7 탭 바에서 비활성 아이콘 / 텍스트 색상을 어떻게 변경할 수 있습니까? 회색 색상입니다.

여기에 이미지 설명 입력


각 TabBar의 모든 첫 번째 ViewController에서 :

- (void)viewDidLoad
{
    [super viewDidLoad];

    // changing the unselected image color, you should change the selected image 
    // color if you want them to be different
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"yourImage_selectedImage"]
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    self.tabBarItem.image = [[UIImage imageNamed:@"yourImage_image"] 
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

이 코드의 단서는 'UIImageRenderingModeAlwaysOriginal'입니다.

Apple 문서의 렌더링 모드 :

UIImageRenderingModeAutomatic,          // Use the default rendering mode for the context where the image is used    
UIImageRenderingModeAlwaysOriginal,     // Always draw the original image, without treating it as a template
UIImageRenderingModeAlwaysTemplate,     // Always draw the image as a template image, ignoring its color information

텍스트 색상을 변경하려면 :

AppDelegate에서 :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Add this if you only want to change Selected Image color 
    // and/or selected image text
    [[UITabBar appearance] setTintColor:[UIColor redColor]];

    // Add this code to change StateNormal text Color,
    [UITabBarItem.appearance setTitleTextAttributes:
    @{NSForegroundColorAttributeName : [UIColor greenColor]} 
    forState:UIControlStateNormal];

    // then if StateSelected should be different, you should add this code
    [UITabBarItem.appearance setTitleTextAttributes:
    @{NSForegroundColorAttributeName : [UIColor purpleColor]} 
    forState:UIControlStateSelected];

    return YES;
}

Render As자산 카탈로그 내에서 탭 표시 줄 이미지 의 속성 을 직접 설정할 수도 있습니다. 속성을 Default, Original Image로 설정할 수있는 옵션이 있습니다 Template Image.

이미지의 렌더링 옵션 설정


탭바의 선택 해제 아이콘 색상 변경

iOS 10 이하 :

// this code need to be placed on home page of tabbar    
for(UITabBarItem *item in self.tabBarController.tabBar.items) {
    item.image = [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

iOS 10 이상 :

// this need to be in appdelegate didFinishLaunchingWithOptions
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]];

모든 UIViewController에 추가하는 대신 확장을 만들고 UITabBarController의 모양을 변경할 수 있습니다.

선택하지 않은 아이콘 색상 변경

extension UITabBarController {
    override public func viewDidLoad() {
        super.viewDidLoad()

        tabBar.items?.forEach({ (item) -> () in
           item.image = item.selectedImage?.imageWithColor(UIColor.redColor()).imageWithRenderingMode(.AlwaysOriginal)
        })
    }
}

선택한 아이콘 색상 변경

let tabBarAppearance = UITabBar.appearance()
tabBarAppearance.tintColor = UIColor.blackColor()

선택하지 않은 제목 색상 변경

let tabBarItemApperance = UITabBarItem.appearance()
tabBarItemApperance.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Edmondsans-Bold", size: 10)!, NSForegroundColorAttributeName:UIColor.redColor()], forState: UIControlState.Normal)
tabBarItemApperance.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Edmondsans-Bold", size: 10)!, NSForegroundColorAttributeName:UIColor.blackColor()], forState: UIControlState.Selected)

UIImage 확장

extension UIImage {
    func imageWithColor(color1: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color1.setFill()

        let context = UIGraphicsGetCurrentContext()
        CGContextTranslateCTM(context!, 0, self.size.height)
        CGContextScaleCTM(context!, 1.0, -1.0);
        CGContextSetBlendMode(context!, .Normal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        CGContextClipToMask(context!, rect, self.CGImage!)
        CGContextFillRect(context!, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

appdelegate.m 만 사용하여 각 ViewController를 사용하지 않고 더 나은 방법이 있습니다.

귀하의 AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions기능에서 이것을 시도하십시오.

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UITabBar *tabBar = tabBarController.tabBar;

// repeat for every tab, but increment the index each time
UITabBarItem *firstTab = [tabBar.items objectAtIndex:0];

// also repeat for every tab
firstTab.image = [[UIImage imageNamed:@"someImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
firstTab.selectedImage = [[UIImage imageNamed:@"someImageSelected.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

파란색 대신 탭 선택 색상을 변경하려면 :

  1. tabItem을 선택합니다.
  2. 오른쪽 메뉴의 "Identity inspector 표시"에서.
  3. 선호하는 색상으로 "tintColor"속성을 설정합니다.

여기에 이미지 설명 입력


Swift 3을 사용하는 iOS 10 이상에서 프로그래밍 방식으로이 작업을 수행하는 새로운 답변은 unselectedItemTintColorAPI 를 사용하는 것 입니다. 예를 들어에서 탭 막대 컨트롤러를 초기화 한 경우 AppDelegate다음과 같이 표시됩니다.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        ...

        let firstViewController = VC1()
        let secondViewController = VC2()
        let thirdViewController = VC3()


        let tabBarCtrl = UITabBarController()
        tabBarCtrl.viewControllers = [firstViewController, secondViewController, thirdViewController]

        // set the color of the active tab
        tabBarCtrl.tabBar.tintColor = UIColor.white

        // set the color of the inactive tabs
        tabBarCtrl.tabBar.unselectedItemTintColor = UIColor.gray

        // set the text color

        ...
    }

선택 및 선택되지 않은 텍스트 색상을 설정하려면 :

let unselectedItem = [NSForegroundColorAttributeName: UIColor.green]
let selectedItem = [NSForegroundColorAttributeName: UIColor.red]

self.tabBarItem.setTitleTextAttributes(unselectedItem, for: .normal)
self.tabBarItem.setTitleTextAttributes(selectedItem, for: .selected)

Swift 3.0에서는 다음과 같이 작성할 수 있습니다.

선택하지 않은 탭 표시 줄 이미지

viewController.tabBarItem.image = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)

선택한 탭 표시 줄 이미지

viewController.tabBarItem.selectedImage = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)

tabBarItem의 각 viewController에 렌더링 이미지 코드를 추가하는 대신 확장을 사용하십시오.

extension UITabBar{
     func inActiveTintColor() {
        if let items = items{
            for item in items{
                item.image =  item.image?.withRenderingMode(.alwaysOriginal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.green], for: .normal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .selected)
            }
        }
    }
}

그런 다음 UITabBarController 클래스에서 다음과 같이 호출하십시오.

class CustomTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.inActiveTintColor()
    }
}

You will get output like : 여기에 이미지 설명 입력 NOTE: Don't forget to assign CustomTabBarViewController class to your TabBarController in storyboard.


I think @anka's answer is quite good, and I also added the following code to enable tint color for highlighted items:

    let image = UIImage(named:"tab-account")!.imageWithRenderingMode(.AlwaysTemplate)
    let item = tabBar.items![IC.const.tab_account] as! UITabBarItem
    item.selectedImage = image

Or in one line:

    (tabBar.items![IC.const.tab_account] as! UITabBarItem).selectedImage = UIImage(named:"tab-account")!.imageWithRenderingMode(.AlwaysTemplate)

So it looks like:

탭바


You only need put this code in your first ViewController called for TabBarViewController (ViewDidload):

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self loadIconsTabBar];
}

-(void) loadIconsTabBar{
        UITabBar *tabBar = self.tabBarController.tabBar;
        //
        UITabBarItem *firstTab = [tabBar.items objectAtIndex:0];
        UITabBarItem *secondTab = [tabBar.items objectAtIndex:1];
        firstTab.image = [[UIImage imageNamed:@"icono1.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
        firstTab.selectedImage = [[UIImage imageNamed:@"icono1.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        secondTab.image = [[UIImage imageNamed:@"icono2.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
        secondTab.selectedImage = [[UIImage imageNamed:@"icono2.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    }

You only need put this code in your appDelegate.m called (didFinishLaunchingWithOptions):

[UITabBarItem.appearance setTitleTextAttributes:
@{NSForegroundColorAttributeName : [UIColor whiteColor]}
                                       forState:UIControlStateNormal];


[UITabBarItem.appearance setTitleTextAttributes:
@{NSForegroundColorAttributeName : [UIColor orangeColor]}
                                       forState:UIControlStateSelected];

[[UITabBar appearance] setTintColor:[UIColor whiteColor]]; // for unselected items that are gray
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor whiteColor]]; 

If you are looking for an iOS 11 swift 4 solution, do something like this in the appDelegate. This is changing all the unselected ones to black.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UITabBar.appearance().unselectedItemTintColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 1)

    return true
}

The best way to change the color of the Selected tab bar item is add a single code on appdelegate didFinishLaunchingWithOptions method

UITabBar.appearance().tintColor = UIColor(red: 242/255.0, green: 32/255.0, blue: 80/255.0, alpha: 1.0)

It will change the selected item text color


인터페이스 빌더를 통해 모든 작업을 수행 할 수 있습니다.이 답변을 확인하고 활성 및 비활성을 모두 수행하는 방법을 보여줍니다. "스토리 보드에서 탭 막대 항목 선택한 색상 변경"


신속한 3 :

    // both have to declare in view hierarchy method
    //(i.e: viewdidload, viewwillappear) according to your need.

    //this one is, when tab bar is selected
    self.tabBarItem.selectedImage = UIImage.init(named: "iOS")?.withRenderingMode(.alwaysOriginal)

    // this one is when tab bar is not selected
    self.tabBarItem.image = UIImage.init(named: "otp")?.withRenderingMode(.alwaysOriginal)

이것은 나를 위해 일했습니다 SWIFT 3

viewConroller.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "image")?.withRenderingMode(.alwaysOriginal),
                                selectedImage:  UIImage(named: "image"))

신속한 솔루션 : UNSELECED 항목 : 모든 ViewController-> ViewDidLoad ()

self.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "PHOTO_NAME")?.imageWithRenderingMode(.AlwaysOriginal), selectedImage: UIImage(named: "NAME"))

참고 URL : https://stackoverflow.com/questions/22767098/how-to-change-inactive-icon-text-color-on-tab-bar

반응형