아이폰 네비게이션바 제목 텍스트 색상
iOS 네비게이션 바의 타이틀 컬러는 기본적으로 흰색인 것 같습니다.다른 색으로 바꿀 수 있는 방법이 있나요?
는 그 일을 알고 있다.navigationItem.titleView이치노디자인 실력에 한계가 있고 표준 광택을 얻지 못했기 때문에 텍스트 색상을 변경하는 것을 선호합니다.
어떤 통찰이라도 감사할 것입니다.
현대적 접근법
현대적인 방법으로는 전체 내비게이션 컨트롤러에 대해 내비게이션 컨트롤러의 루트 뷰가 로드되면 이 작업을 한 번 수행합니다.
[self.navigationController.navigationBar setTitleTextAttributes:
@{NSForegroundColorAttributeName:[UIColor yellowColor]}];
그러나, 이것은 이후의 관점에서는 효과가 없는 것 같습니다.
클래식한 어프로치
기존 방식으로는 뷰별 컨트롤러(이러한 상수는 iOS 6용이지만 iOS 7 외관의 뷰별 컨트롤러별 상수는 동일하지만 상수가 다른 접근 방식이 필요합니다.)
하다를 요.UILabel처 titleViewnavigationItem.
라벨은 다음과 같습니다.
- 하다.
label.backgroundColor = [UIColor clearColor]를 참조해 주세요. - 글씨 글꼴20pt')을 합니다.
label.font = [UIFont boldSystemFontOfSize: 20.0f]를 참조해 주세요. - 가 50.
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]를 참조해 주세요. - 하는 것이
label.textAlignment = NSTextAlignmentCenter)UITextAlignmentCenter」)
원하는 사용자 지정 색상으로 레이블 텍스트 색상을 설정합니다.텍스트가 음영으로 섞이지 않는 색을 원하기 때문에 읽기 어렵습니다.
시행착오를 겪으며 이 문제를 해결했지만, 내가 생각해낸 가치들은 결국 애플이 선택한 것과 같지 않기에는 너무 단순하다.:)
하려면 , 이 를 「 the Code」(으)로 해 .initWithNibName:bundle:PageThreeViewController.mApple의 NavBar 샘플입니다.그러면 텍스트가 노란색 라벨로 바뀝니다.이것은 색을 제외하고는 애플의 코드에 의해 만들어진 원본과 구별할 수 없을 것입니다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// this will appear as the title in the navigation bar
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = NSTextAlignmentCenter;
// ^-Use UITextAlignmentCenter for older SDKs.
label.textColor = [UIColor yellowColor]; // change this color
self.navigationItem.titleView = label;
label.text = NSLocalizedString(@"PageThreeTitle", @"");
[label sizeToFit];
}
return self;
}
편집: 또한 아래 에릭 B의 답변을 읽어보세요.내 코드는 효과를 나타내지만, 그의 코드는 이것을 기존 뷰 컨트롤러에 놓을 수 있는 더 간단한 방법을 제공합니다.
꽤 오래된 스레드인 것은 알지만, iOS 5가 타이틀 속성을 확립하기 위한 새로운 속성을 가져온다는 것을 새 사용자에게 알려두면 도움이 될 것 같습니다.
의 UINavigation Bar를 할 수 .setTitleTextAttributes글꼴, 색상, 오프셋 및 그림자 색상을 설정합니다.
모든 UINavigation Bar에 대해 UINavigation할 수 .UINavigationBars전체 어플리케이션에서 사용할 수 있습니다.
예를 들어 다음과 같습니다.
NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],UITextAttributeTextColor,
[UIColor blackColor], UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(-1, 0)], UITextAttributeTextShadowOffset, nil];
[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
iOS 5에서는 다음과 같은 방법으로 탐색 모음 제목 색상을 변경할 수 있습니다.
navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
스티븐 피셔의 대답에 기초하여 나는 다음과 같은 코드를 작성했다.
- (void)setTitle:(NSString *)title
{
[super setTitle:title];
UILabel *titleView = (UILabel *)self.navigationItem.titleView;
if (!titleView) {
titleView = [[UILabel alloc] initWithFrame:CGRectZero];
titleView.backgroundColor = [UIColor clearColor];
titleView.font = [UIFont boldSystemFontOfSize:20.0];
titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleView.textColor = [UIColor yellowColor]; // Change to desired color
self.navigationItem.titleView = titleView;
[titleView release];
}
titleView.text = title;
[titleView sizeToFit];
}
이 코드의 장점은 프레임을 적절하게 처리하는 것 외에 컨트롤러의 제목을 변경하면 커스텀타이틀 뷰도 갱신됩니다.수동으로 갱신할 필요는 없습니다.
또 다른 큰 장점은 커스텀 타이틀 컬러를 매우 간단하게 사용할 수 있다는 것입니다.이 방법을 컨트롤러에 추가하기만 하면 됩니다.
위의 제안의 대부분은 iOS 7에서는 권장되지 않습니다.
NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],NSForegroundColorAttributeName,
[UIColor whiteColor],NSBackgroundColorAttributeName,nil];
self.navigationController.navigationBar.titleTextAttributes = textAttributes;
self.title = @"Title of the Page";
또한 설정할 수 있는 다양한 텍스트속성에 대해서도 NSAttribedString.h를 체크합니다.
IOS 7 및 8에서는 제목 색상을 녹색으로 변경할 수 있습니다.
self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
질문을 최신 상태로 유지하기 위해 Alex R. R. 솔루션을 추가하지만 Swift에서는 다음과 같이 설명합니다.
self.navigationController.navigationBar.barTintColor = .blueColor()
self.navigationController.navigationBar.tintColor = .whiteColor()
self.navigationController.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.whiteColor()
]
그 결과:
스위프트 버전
여러분 대부분이 Objective_C 버전의 답을 제시해 주셨습니다.
Swift를 사용하여 필요한 사람을 위해 이 기능을 구현하고 싶습니다.
View Didload 중
1. Navigation Bar 배경을 컬러로 하려면(예: BLUE)
self.navigationController?.navigationBar.barTintColor = UIColor.blueColor()
2. Navigation Bar 배경을 Image로 하려면 (예를 들어 ABC.png)
let barMetrix = UIBarMetrics(rawValue: 0)!
self.navigationController?.navigationBar
.setBackgroundImage(UIImage(named: "ABC"), forBarMetrics: barMetrix)
3. Navigation Bar 제목을 변경하려면 (예: [Font:후투라, 10] [색상 :빨강])
navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont(name: "Futura", size: 10)!
]
(hint1:UIFont 뒤에 "!" 마크를 잊지 마세요)
(hint2: 제목 텍스트에 많은 속성이 있습니다.명령어를 사용하여 "NSFontAttributeName"을 클릭하면 클래스를 입력하고 keyNames 및 필요한 오브젝트 유형을 볼 수 있습니다.)
도움이 되었으면 합니다!:d
방법 1, IB에서 설정합니다.
방법 2, 코드 한 줄:
navigationController?.navigationBar.barTintColor = UIColor.blackColor()
tewa의 솔루션은 페이지의 색상을 바꾸려고 하면 잘 되지만, 모든 페이지의 색상을 변경할 수 있도록 하고 싶습니다.의 모든 페이지에 사용할 수 있도록 약간의 수정을 가했습니다.UINavigationController
NavigationDelegate.h
//This will change the color of the navigation bar
#import <Foundation/Foundation.h>
@interface NavigationDelegate : NSObject<UINavigationControllerDelegate> {
}
@end
NavigationDelegate.m
#import "NavigationDelegate.h"
@implementation NavigationDelegate
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
CGRect frame = CGRectMake(0, 0, 200, 44);//TODO: Can we get the size of the text?
UILabel* label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor yellowColor];
//The two lines below are the only ones that have changed
label.text=viewController.title;
viewController.navigationItem.titleView = label;
}
@end
iOS 5 이후로는 제목을 사용하여 네비게이션 바의 제목 텍스트 색상과 글꼴을 설정해야 합니다.TextAttribute Dictionary(UI 탐색 컨트롤러 클래스 참조에 미리 정의된 사전).
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor blackColor],UITextAttributeTextColor,
[UIFont fontWithName:@"ArialMT" size:16.0], UITextAttributeFont,nil]];
짧고 달콤하다.
[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
뷰 컨트롤러 viewDidLoad 또는 viewWillAple 메서드에서 다음 코드를 사용합니다.
- (void)viewDidLoad
{
[super viewDidLoad];
//I am using UIColor yellowColor for an example but you can use whatever color you like
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
//change the title here to whatever you like
self.title = @"Home";
// Do any additional setup after loading the view.
}
이건 스티븐스를 기반으로 한 제 해결책입니다
실제적인 차이는 텍스트 길이에 따라 애플과 비슷한 것 같으면 위치를 조정하기 위해 약간의 핸들링을 넣는 것입니다.
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft), 0, 480,44)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.font = [UIFont boldSystemFontOfSize: 20.0f];
titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleLabel.textAlignment = ([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft);
titleLabel.textColor = [UIColor redColor];
titleLabel.text = self.title;
self.navigationItem.titleView = titleLabel;
[titleLabel release];
글꼴 크기에 따라 10 값을 조정할 수 있습니다.
Swift 4.2 버전:
self.navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
(버튼이 1개밖에 없을 때) 네비게이션 버튼이 텍스트를 가운데에서 떨어뜨리는 문제에 부딪혔습니다.프레임 크기를 이렇게 변경했습니다.
CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
네비게이션 바의 배경 이미지와 왼쪽 버튼 항목을 커스터마이즈하여 회색 제목이 배경에 맞지 않습니다.다음으로 다음을 사용합니다.
[self.navigationBar setTintColor:[UIColor darkGrayColor]];
색조를 회색으로 변경합니다.그리고 지금 제목은 하얀색이에요!그게 내가 원하는 거야.
도움이 되었으면 합니다. :)
자녀용 네비게이션 바를 누르거나 탭 바에 제목을 표시할 때 사용되므로 self.title을 설정하는 것이 좋습니다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// create and customize title view
self.title = NSLocalizedString(@"My Custom Title", @"");
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.text = self.title;
titleLabel.font = [UIFont boldSystemFontOfSize:16];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;
[titleLabel release];
}
}
꽤 오래된 스레드이지만 iOS 7 이상에서 내비게이션 바의 색상, 크기, 수직 위치 설정에 대한 답변을 제공하려고 합니다.
색상 및 크기
NSDictionary *titleAttributes =@{
NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
NSForegroundColorAttributeName : [UIColor whiteColor]
};
수직 위치용
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-10.0 forBarMetrics:UIBarMetricsDefault];
제목 설정 및 속성 사전 할당
[[self navigationItem] setTitle:@"CLUBHOUSE"];
self.navigationController.navigationBar.titleTextAttributes = titleAttributes;
Swift에서는 이 방법이 유효합니다.
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
self.navigationItem.title=@"Extras";
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:21], NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];
오리엔테이션 지원에 이렇게 사용
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
[view setBackgroundColor:[UIColor clearColor]];
[view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];
UILabel *nameLabel = [[UILabel alloc] init];
[nameLabel setFrame:CGRectMake(0, 0, 320, 40)];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setFont:[UIFont boldSystemFontOfSize:17]];
[nameLabel setText:titleString];
[nameLabel setTextAlignment:UITextAlignmentCenter];
[view addSubview:nameLabel];
[nameLabel release];
self.navigationItem.titleView = view;
[view release];
내가 사용한 제목의 글꼴 크기를 설정하려면 다음과 같은 조건을 사용합니다.누구에게나 도움이 될지도 모른다
if ([currentTitle length]>24) msize = 10.0f;
else if ([currentTitle length]>16) msize = 14.0f;
else if ([currentTitle length]>12) msize = 18.0f;
Alex R. R.의 투고 갱신.새로운 iOS 7 텍스트 속성과 최신 목표 c를 사용하여 노이즈를 줄였습니다.
NSShadow *titleShadow = [[NSShadow alloc] init];
titleShadow.shadowColor = [UIColor blackColor];
titleShadow.shadowOffset = CGSizeMake(-1, 0);
NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
NSShadowAttributeName:titleShadow};
[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
나는 의 색상을 설정하는 적절한 방법을 믿는다.UINavigationBar 말합니다
NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil];
self.titleTextAttributes = attributes;
위의 코드는 다음 서브클래스입니다.UINavigationBar는 서브클래스 없이 동작합니다.
이건 빠진 것들 중 하나야.사용자 정의 탐색 막대를 만들고 텍스트 상자를 추가한 다음 색상을 조작하는 것이 가장 좋습니다.
NavBar에 버튼을 삽입할 때 라벨이 움직이는 것과 같은 문제가 발생한 후(내 경우 날짜가 로드될 때 버튼으로 교체하는 스피너가 있습니다), 위의 해결 방법이 작동하지 않았습니다.따라서 라벨을 항상 같은 위치에 유지한 방법은 다음과 같습니다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// this will appear as the title in the navigation bar
//CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
CGRect frame = CGRectMake(0, 0, 180, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor yellowColor];
self.navigationItem.titleView = label;
label.text = NSLocalizedString(@"Latest Questions", @"");
[label sizeToFit];
}
return self;
다른 버튼이 탐색 막대를 사용할 때 레이블이 제목 보기에서 자동으로 재배치되는 이상한 오프셋을 방지하기 위해 텍스트를 설정한 후 [label sizeToFit]을 호출해야 합니다.
이 메서드는 위임 파일에서 사용할 수 있으며 모든 보기에서 사용할 수 있습니다.
+(UILabel *) navigationTitleLable:(NSString *)title
{
CGRect frame = CGRectMake(0, 0, 165, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = NAVIGATION_TITLE_LABLE_SIZE;
label.shadowColor = [UIColor whiteColor];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeTailTruncation;
label.textAlignment = UITextAlignmentCenter;
[label setShadowOffset:CGSizeMake(0,1)];
label.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
//label.text = NSLocalizedString(title, @"");
return label;
}
titleTextAttributes 막대의 제목 텍스트에 대한 속성을 표시합니다.
@property(비원자성, 복사) NSDirectionary *제목텍스트 속성 토론 NSString UIKit Additions Reference에서 설명하는 텍스트 속성 키를 사용하여 텍스트 속성 사전에서 제목의 글꼴, 텍스트 색상, 텍스트 그림자 색상 및 텍스트 그림자 오프셋을 지정할 수 있습니다.
가용성 iOS 5.0 이상에서 사용 가능.UINavigationBar.h로 선언됨
언급URL : https://stackoverflow.com/questions/599405/iphone-navigation-bar-title-text-color
'source' 카테고리의 다른 글
| 사용되지 않는 크기의 대체With Font: iOS 7? (0) | 2023.04.17 |
|---|---|
| 삽입 명령 실행 및 SQL에 삽입된 ID 반환 (0) | 2023.04.17 |
| [NSObject description]의 Swift는 무엇입니까? (0) | 2023.04.17 |
| std:: 문자열을 int로 변환하려면 어떻게 해야 하나요? (0) | 2023.04.17 |
| Swift - 방향 변화를 감지하는 방법 (0) | 2023.04.17 |

