program tip

UITabBar의 색조 / 배경색 변경

radiobox 2020. 9. 13. 10:18
반응형

UITabBar의 색조 / 배경색 변경


UINavigationBar 및 UISearchBar에는 두 항목 모두의 색조 색상을 변경할 수있는 tintColor 속성이 있습니다. 내 응용 프로그램의 UITabBar에 동일한 작업을 수행하고 싶지만 이제 기본 검은 색에서 변경하는 방법을 찾았습니다. 어떤 아이디어?


UITabBarController를 서브 클래 싱하고 개인 클래스를 사용하여 작동하도록 만들 수있었습니다.

@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end

@implementation CustomUITabBarController


- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    [v setBackgroundColor:kMainColor];
    [v setAlpha:0.5];
    [[self tabBar] addSubview:v];
    [v release];

}
@end

iOS 5에는 대부분의 UI 요소의 모양을 사용자 정의하기위한 몇 가지 새로운 모양 방법이 추가되었습니다.

모양 프록시를 사용하여 앱에서 UITabBar의 모든 인스턴스를 대상으로 지정할 수 있습니다.

iOS 5 + 6 :

[[UITabBar appearance] setTintColor:[UIColor redColor]];

iOS 7 이상의 경우 다음을 사용하십시오.

[[UITabBar appearance] setBarTintColor:[UIColor redColor]];

모양 프록시를 사용하면 앱 전체에서 탭 모음 인스턴스가 변경됩니다. 특정 인스턴스의 경우 해당 클래스의 새 속성 중 하나를 사용합니다.

UIColor *tintColor; // iOS 5+6
UIColor *barTintColor; // iOS 7+
UIColor *selectedImageTintColor;
UIImage *backgroundImage;
UIImage *selectionIndicatorImage;

최종 답변에 대한 부록이 있습니다. 필수 구성표는 정확하지만 부분적으로 투명한 색상을 사용하는 트릭을 개선 할 수 있습니다. 나는 그것이 기본 그라디언트를 보여주기위한 것이라고 가정합니다. 아, 또한 TabBar의 높이는 적어도 OS 3에서 48 픽셀이 아닌 49 픽셀입니다.

따라서 그래디언트가있는 적절한 1 x 49 이미지가있는 경우 다음을 사용해야하는 viewDidLoad 버전입니다.

- (void)viewDidLoad {

    [super viewDidLoad]; 

    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    UIImage *i = [UIImage imageNamed:@"GO-21-TabBarColorx49.png"];
    UIColor *c = [[UIColor alloc] initWithPatternImage:i];
    v.backgroundColor = c;
    [c release];
    [[self tabBar] addSubview:v];
    [v release];

}

addSubview를 사용하면 버튼이 클릭 가능성을 잃게됩니다.

[[self tabBar] addSubview:v];

사용하다:

[[self tabBar] insertSubview:v atIndex:0];

이 작업을 수행하는 간단한 방법은 없습니다. 기본적으로 UITabBar를 하위 클래스로 만들고 원하는 작업을 수행하기 위해 사용자 정의 드로잉을 구현해야합니다. 효과를 위해 꽤 많은 작업이지만 그만한 가치가있을 수 있습니다. 향후 iPhone SDK에 추가하려면 Apple에 버그를 제출하는 것이 좋습니다.


다음은이를위한 완벽한 솔루션입니다. 이것은 iOS5 및 iOS4에서 잘 작동합니다.

//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar]; 

if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}

On iOS 7:

[[UITabBar appearance] setBarTintColor:[UIColor colorWithRed:(38.0/255.0) green:(38.0/255.0) blue:(38.0/255.0) alpha:1.0]];

I also recommend setting first depending on your visual desires:

[[UITabBar appearance] setBarStyle:UIBarStyleBlack];

The bar style puts a subtle separator between your view content and your tab bar.


[[self tabBar] insertSubview:v atIndex:0]; works perfectly for me.


for me its very simple to change the color of Tabbar like :-

[self.TabBarController.tabBar setTintColor:[UIColor colorWithRed:0.1294 green:0.5686 blue:0.8353 alpha:1.0]];


[self.TabBarController.tabBar setTintColor:[UIColor "YOUR COLOR"];

Try this!!!


 [[UITabBar appearance] setTintColor:[UIColor redColor]];
 [[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];

for just background color

Tabbarcontroller.tabBar.barTintColor=[UIColor redcolour];

or this in App Delegate

[[UITabBar appearance] setBackgroundColor:[UIColor blackColor]];

for changing color of unselect icons of tabbar

For 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];
}

Above iOS 10:

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

There are some good ideas in the existing answers, many work slightly differently and what you choose will also depend on which devices you target and what kind of look you're aiming to achieve. UITabBar is notoriously unintuitive when it come to customizing its appearance, but here are a few more tricks that may help:

1). If you're looking to get rid of the glossy overlay for a more flat look do:

tabBar.backgroundColor = [UIColor darkGrayColor]; // this will be your background
[tabBar.subviews[0] removeFromSuperview]; // this gets rid of gloss

2). To set custom images to the tabBar buttons do something like:

for (UITabBarItem *item in tabBar.items){
    [item setFinishedSelectedImage:selected withFinishedUnselectedImage:unselected];
    [item setImageInsets:UIEdgeInsetsMake(6, 0, -6, 0)];
}

Where selected and unselected are UIImage objects of your choice. If you'd like them to be a flat colour, the simplest solution I found is to create a UIView with the desired backgroundColor and then just render it into a UIImage with the help of QuartzCore. I use the following method in a category on UIView to get a UIImage with the view's contents:

- (UIImage *)getImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [[UIScreen mainScreen]scale]);
    [[self layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

3) Finally, you may want to customize the styling of the buttons' titles. Do:

for (UITabBarItem *item in tabBar.items){
    [item setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                [UIColor redColor], UITextAttributeTextColor,
                [UIColor whiteColor], UITextAttributeTextShadowColor,
                [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
                [UIFont boldSystemFontOfSize:18], UITextAttributeFont,
            nil] forState:UIControlStateNormal];
}

This lets you do some adjustments, but still quite limited. Particularly, you cannot freely modify where the text is placed within the button, and cannot have different colours for selected/unselected buttons. If you want to do more specific text layout, just set UITextAttributeTextColor to be clear and add your text into the selected and unselected images from part (2).


[v setBackgroundColor ColorwithRed: Green: Blue: ];

Another solution (which is a hack) is to set the alpha on the tabBarController to 0.01 so that it is virtually invisible yet still clickable. Then set a an ImageView control on the bottom of the MainWindow nib with your custom tabbar image underneath the alpha'ed tabBarCOntroller. Then swap the images, change colors or hightlight when the tabbarcontroller switches views.

However, you lose the '...more' and customize functionality.


Hi There am using iOS SDK 4 and i was able to solve this issue with just two lines of code and it's goes like this

tBar.backgroundColor = [UIColor clearColor];
tBar.backgroundImage = [UIImage imageNamed:@"your-png-image.png"];

Hope this helps!


if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}

Swift 3.0 answer: (from Vaibhav Gaikwad)

For changing color of unselect icons of tabbar:

if #available(iOS 10.0, *) {
        UITabBar.appearance().unselectedItemTintColor = UIColor.white
    } else {
        // Fallback on earlier versions
        for item in self.tabBar.items! {
            item.image = item.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        }
}

For changing text color only:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal)

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red, for: .selected)

Swift 3 using appearance from your AppDelegate do the following:

UITabBar.appearance().barTintColor = your_color

참고URL : https://stackoverflow.com/questions/571028/changing-tint-background-color-of-uitabbar

반응형