Ответ 1
Это работает. Дать кадр во время инициализации
UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[iv setBackgroundColor:[UIColor whiteColor]];
self.navigationItem.titleView = iv;
Я пытаюсь добавить пользовательский вид в центре панели навигации в iOS5, и я использую следующий код для его проверки:
UIView * testView = [[UIView alloc] init];
[testView setBackgroundColor:[UIColor blackColor]];
testView.frame = CGRectMake(0, 0, 100, 35);
[self.navigationController.navigationItem.titleView addSubview:testView];
Я устанавливаю это в методе viewDidLoad моего контроллера представления, но когда я запускаю свою программу ничего не меняется в моей навигационной панели.
Не могли бы вы мне помочь?
Большое спасибо.
Это работает. Дать кадр во время инициализации
UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[iv setBackgroundColor:[UIColor whiteColor]];
self.navigationItem.titleView = iv;
Если вы хотите просто настроить заголовок для одного контроллера вида, вы можете использовать
UILabel *lblTitle = [[UILabel alloc] init];
lblTitle.text = @"Diga-nos o motivo";
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0];
lblTitle.shadowColor = [UIColor whiteColor];
lblTitle.shadowOffset = CGSizeMake(0, 1);
lblTitle.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0];
[lblTitle sizeToFit];
self.navigationItem.titleView = lblTitle;
или если вы хотите настроить для всех контроллеров представления, используйте
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0],
UITextAttributeTextColor,
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],
UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
UITextAttributeTextShadowOffset,
[UIFont fontWithName:@"Arial-Bold" size:10.0],
UITextAttributeFont,
nil]];
Заменить
[self.navigationController.navigationItem.titleView addSubview:testView];
к
self.navigationItem.titleView = testView;
Примечание. Вы не можете добавить subviews в titleView, потому что значение по умолчанию равно nil
, вам нужно установить новое представление как titleView.
CustomLabel *titleLabel = [CustomLabel initWithLabelFrame:labelFrame textFont:[UIFont fontWithName:@"Helvetica" size:[UIFont systemFontSize]] textColor:[UIColor blackColor] labelText:@"Add as" textAlignment:NSTextAlignmentCenter labelOnView:reference.view labelTag:62];
[self.navigationItem setTitleView:titleLabel]; // titleLabel set in navigationItem
Вы хотите использовать раскадровку для этого, чтобы поддерживать iPhone 6 и более новые (более крупные) устройства.
Создайте представление контейнера для заголовка/субтитров настраиваемого элемента навигации и перетащите его в визуальный редактор (не в иерархию представления).
#import <UIKit/UIKit.h>
@interface MasterViewController : UITableViewController
@end
#import "MasterViewController.h"
@interface MasterViewController ()
@end
@implementation MasterViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.titleView = [self titleView];
}
- (UIView *)titleView {
CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
CGFloat width = 0.95 * self.view.frame.size.width;
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, navBarHeight)];
UIImage *logo = [UIImage imageNamed:@"logo.png"];
UIButton *logoButton = [UIButton buttonWithType:UIButtonTypeCustom];
CGFloat logoY = floorf((navBarHeight - logo.size.height) / 2.0f);
[logoButton setFrame:CGRectMake(0, logoY, logo.size.width, logo.size.height)];
[logoButton setImage:logo forState:UIControlStateNormal];
UIImage *bubble = [UIImage imageNamed:@"notification-bubble-empty.png"];
UIImageView *bubbleView = [[UIImageView alloc] initWithImage:bubble];
const CGFloat Padding = 5.0f;
CGFloat bubbleX =
logoButton.frame.size.width +
logoButton.frame.origin.x +
Padding;
CGFloat bubbleY = floorf((navBarHeight - bubble.size.height) / 2.0f);
CGRect bubbleRect = bubbleView.frame;
bubbleRect.origin.x = bubbleX;
bubbleRect.origin.y = bubbleY;
bubbleView.frame = bubbleRect;
[containerView addSubview:logoButton];
[containerView addSubview:bubbleView];
return containerView;
}
@end
Swift 3
let myImageView = UIImageView(image: <...set your image...>)
override fun viewDidLoad(){
super.viewDidLoad()
self.navigationItem.titleView = myImageView //
}
Еще одно альтернативное решение -
override fun viewWillAppear(<...>){
super. viewWillAppear(<...>)
self.navigationItem.titleView = myImageView
}
Я рекомендую использовать viewDidLoad для настройки titleView