2013-08-27 39 views
0

我有一個根視圖控制器,我需要知道如何將它的藍色背景更改爲圖像或更改其顏色,還希望將圖像添加到其右側。 例如,在下面的圖像中,我需要將文本根視圖控制器的背景更改爲另一個圖像或更改其顏色,並在根視圖控制器文本的右側添加一個小圖標。我應該怎麼做呢?我已經通過Change Navigation bar Background image on each navigation,但仍然無法實現它。更改導航項目的背景並添加圖像

AppDelegate.h

#import <UIKit/UIKit.h> 

@interface AppDelegate : UIResponder <UIApplicationDelegate> 

@property (strong, nonatomic) UIWindow *window; 

@end 

Viewcontroller.h

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 

@end 

​​

+0

你有沒有嘗試這個? [[UINavigationBar appearance] setBackgroundImage:@「navImage」forBarMetrics:UIBarMetricsDefault]; – karthika

+0

假設你在iOS 5+上工作? –

+0

我正在使用xcode 4.2需要儘快升級:P – Gamerlegend

回答

1

嘗試將這些代碼放入ViewWillAppear/ViewDidAppear/didFinishLaunchingWithOptions(在appDelegate的情況下)。

1)navigationItem.titleView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"urtitlebar.png"]];

OR

2)

UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; 
UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage  imageNamed:@"urtitlebar.png"]]; 
[image setFrame:CGRectMake(0, 0, 44, 44)]; 
[myView addSubview:image]; 
[self.navigationController.navigationBar addSubview:myView]; 

OR

3)

UINavigationBar *navBar = self.navigationController.navigationBar; 
UIImage *image = [UIImage imageNamed:@"urtitlebar.png"]; 
[navBar setBackgroundImage:image]; 

EDIT:(如果你正在使用舊版本的SDK 3.2.5說)

創建的UINavigationBar子視圖和覆蓋調用的方法 - drawRect:(CGRect)rect用,

@implementation UINavigationBar (BackgroundImage) 

- (void)drawRect:(CGRect)rect 
{ 
    UIImage *navBarImage; 


     image = [UIImage imageNamed: @"urNavigationBar.png"]; 
    } 
    [navBarImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
} 

@end

+0

感謝您的回覆,我幾乎接近您的代碼幫助解決方案,但有一些小麻煩,您的第二個答案是有可能從右側加載setFrame?並在你的第三個答案我得到這個錯誤「接收器類型UINavigationBar例如消息不聲明方法setBackgroundImage」 – Gamerlegend

+0

[image setFrame:CGRectMake(276,0,44,44)]; –

+0

@Gamerlegend ...工作? –

0

嘗試導航欄上的這段代碼在AppDelegate.m的didFinishLaunchingWithOptions自定義圖像。

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"yourImageName.png"] forBarMetrics:UIBarMetricsDefault]; 

您還可以添加自定義按鈕作爲欄按鈕。

// create a custom button in viewDidLoad of your ViewController in which you want to place a custom bar button 
UIButton *customBackBtn =[[UIButton alloc] init]; 
[customBackBtn setBackgroundImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal]; 
customBackBtn.frame = CGRectMake(100, 100, 52, 31); 

// set this customized button as BarButton 
UIBarButtonItem *backBtn =[[UIBarButtonItem alloc] initWithCustomView:customBackBtn]; 
[customBackBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside]; 
self.navigationItem.leftBarButtonItem = backBtn; 

就是這樣。

+0

感謝您的回覆,在您的第一個聲明中可以定位圖像,例如現在圖像顯示從最高到75%,但我只需要顯示中心部分。對於第二部分,我知道要添加自定義按鈕,我試圖在右側添加UIimage而不是按鈕,是否有可能? – Gamerlegend