0

我想在我的UINavigationController中的標題旁邊顯示一個小圖標。在UINavigationController中添加帶有標題的圖像

通過Photoshop中的魔力,就像這樣:

enter image description here

我知道我需要創建一個新的視圖和圖像和標題建成了。下面是我在做什麼:

在viewDidLoad中的UINavigationController的視圖控制器,我調用該方法

[self setTitleBar];

調用該方法:

- (void) setTitleBar { 


    CGRect navBarFrame = self.navigationController.navigationBar.frame; 


    //UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(navBarFrame.origin.x, navBarFrame.origin.y, (leftButtonFrame.origin.x + leftButtonFrame.size.width) - rightButtonFrame.origin.x, navBarFrame.size.height)]; 
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(navBarFrame.origin.x, navBarFrame.origin.y,self.view.frame.size.width,navBarFrame.size.height)]; 
    titleView.backgroundColor = [UIColor clearColor]; 


    CGPoint tvCenter = CGPointMake(titleView.frame.size.width/2, titleView.frame.size.height/2); 

    UIImage * icon = [UIImage imageNamed:@"star"]; 

    UIImageView *iconView = [[UIImageView alloc] initWithImage:icon]; 
    iconView.frame = CGRectMake(0, 0, icon.size.width, icon.size.height); 

    UILabel *title = [[UILabel alloc] init]; 
    title.backgroundColor = [UIColor clearColor]; 
    title.textColor = [UIColor whiteColor]; 
    title.textAlignment = NSTextAlignmentCenter; 
    title.text = @"SOME TITLE"; 
    title.frame = CGRectMake(0, 0, 100, titleView.frame.size.height); 
    [title sizeToFit]; 


    iconView.center = CGPointMake(tvCenter.x - (icon.size.width/2), tvCenter.y); 

    [titleView addSubview:iconView]; 
    [titleView addSubview:title]; 

    self.navigationItem.titleView = titleView; 
} 

我在titleview的邏輯:獲取最左邊的按鈕框架並獲取最右邊的按鈕框架。然後做一些數學來確定視圖有多大。這應該是titleView的框架大小。

但是,我似乎無法得到它的工作。如果我插入的幀大小爲0,0,100,40;然後它顯示框架,但一切都擠在一起。但你看到它。我知道100應該是動態的,以確保顯示標題。

但我似乎無法弄清楚。

任何幫助?

+0

使用'sizeToFit'。這裏是文檔https://developer.apple.com/reference/uikit/uiview/1622630-sizetofit?language=objc。 –

+0

導航欄是否會自動調整視圖大小?如果是這樣,也許你應該在XIB中做這件事,這樣你可以很容易地看到它調整大小時的樣子。 –

回答

0

您可以將對象放置在導航控制器視圖中作爲子視圖。

- (void) setTitleBar { 

    //Let's say your icon size is 20 
    int starSize = 20; 
    //Now you'll have to calculate where to place the ImageView respect the TextSize (for this you'll need to know the text and font of your UINavigationItem title) 
    CGSize textSize = [@"SOME TITLE" sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"navfontname" size:15]}]; 
    UIImageView *startImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.navigationController.view.frame.size.width/2 - textSize.width/2, self.navigationController.view.frame.size.height/2 - starSize/2, starSize,starSize)]; 
    startImageView.image = [UIImage imageNamed:@"star"]; 
    [self.navigationController.view addSubview:startImageView]; 

} 
+0

嗯..我似乎無法得到這個工作。似乎邏輯 –

+0

它是UIImageView作爲子視圖添加到self.navigationController.view?你可以看到它,如果你把它的框架設置爲CGRectMake(0,0,20,20)? –

+0

它將它放置在屏幕中間。 –

相關問題