Adding UINavigation bar programmatically - ios

I was trying to add the navigation bar to the application programmatically but I didn't got any success.
I had tried the code mentioned below
UIBarButtonItem *alefttbarButton = [[UIBarButtonItem alloc] initWithTitle:#"Setting" style:UIBarButtonItemStyleBordered target:self action:#selector(settingAction:)];
alefttbarButton.style = UIBarButtonItemStyleBordered;
alefttbarButton.tintColor= [UIColor redColor];
self.navigationItem.leftBarButtonItem=alefttbarButton;
self.navigationController.delegate=self;
self.title =#"test";

Here's how I did it. In this particular case I created my views all by hand. Starting in the applicationDidFinishLaunching, I have the following code:
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
mainCtl = [[MainController alloc] init];
[window addSubview:mainCtl.nav.view];
[window makeKeyAndVisible];
As you can see I here allocate and initialize an instance of MainController, which is a subclass of UIViewController.
Then, in the initialization of this MainController I have a call to the navigation bar initialization code:
[self initNavBar];
which is the following function:
- (void) initNavBar
{
printf("initNavBar entered\n");
self.nav = [[UINavigationController alloc] initWithRootViewController: self];
//setup the middle view
int btnCount = 4;
CGRect buttonsFrame = CGRectMake(0, 0, btnCount*BUTTONWIDTH + (btnCount-1)*BUTTONSPACING + 2*BUTTONMARGIN, BUTTONHEIGHT + 2*BUTTONMARGIN);
UIView *buttonsView = [[UIView alloc] initWithFrame:buttonsFrame];
UIButton *button;
CGFloat left = BUTTONMARGIN;
// create button for photo selector invocation
button = [self buttonWithName:#"photo" target:self selector:#selector(showImagePicker) left:left];
//button = [self createButton:#"photo" action:#selector(showImagePicker) left:left];
[buttonsView addSubview:button];
left += (BUTTONWIDTH+BUTTONSPACING);
button = [self buttonWithName:#"crop" target:self selector:#selector(cropImage) left:left];
[buttonsView addSubview: button];
left += (BUTTONWIDTH+BUTTONSPACING);
kissButton = [self buttonWithName:#"kiss" target:self selector:#selector(cropImage) left:left];
[buttonsView addSubview: kissButton];
//left += (BUTTONWIDTH+BUTTONSPACING);
left += (BUTTONWIDTH+BUTTONSPACING);
button = [self buttonWithName:#"mail" target:self selector:#selector(showMailDialog) left:left];
//button = [self createButton:#"mail" action:#selector(showMailDialog) left:left];
[buttonsView addSubview:button];
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
//only enable the mail button if the class exists
button.enabled = (mailClass != nil);
printf("initNavBar done\n");
}
This is all working code. If you can look through the cruft you'll manage to get the picture.
Hope this helps.

Related

How to add the view to whole screen

I have an 2 vc,with push from one screen to another screen.In my vc2 programmatically i am adding the nav bar title, bar button . But when i add the view some 10 points from top is reduced. not showing fully. I tried all the possibilities. Attached the image also:
in my vc2 :
- (void)viewDidLoad {
[super viewDidLoad];
_menuView.hidden = YES;
[self navItems];
}
-(void)navItems{
UIImage* filterImage = [UIImage imageNamed:#"filter.png"];
CGRect frameimg = CGRectMake(0,0, 15,15);
filterBtn = [[UIButton alloc] initWithFrame:frameimg];
[filterBtn setBackgroundImage:filterImage forState:UIControlStateNormal];
[filterBtn addTarget:self action:#selector(MenuTap:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *filter =[[UIBarButtonItem alloc] initWithCustomView:filterBtn];
self.navigationItem.rightBarButtonItem = filter;
self.title = #"Demo";
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
- (IBAction)MenuTap:(id)sender
{
_menuView.hidden = NO;
//1
// [self.navigationController.view addSubview:_menuView];
// [self.view addSubview:_menuView];
//2
// UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
// [window addSubview: _menuView];
//
//3
// UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
//[currentWindow addSubview:_menuView];
//4
//[[UIApplication sharedApplication].windows.lastObject addSubview:_menuView];
//5
// self.navigationController.navigationBar.layer.zPosition = -1;
//[self.view addSubview:_menuView];
}
But not able to show fully any idea please ?
based on your question in here added the detail answer, if you want to show below the status bar , then you need to get the status bar height initially, there after you need to add the y position how much you need.
- (IBAction)MenuTap:(id)sender
{
_menuView.hidden = NO;
//initially getStatusbar height
float statusBarHeight = [self statusBarHeight];
// assign your subview to window bounds
_menuView.frame = [[UIScreen mainScreen] bounds];
CGRect frameRect = _menuView.frame;
// convert your y- coordinates based on your need
frameRect.origin.y = statusBarHeight;
_menuView.frame = frameRect;
[self.navigationController.view addSubview:_menuView];
}
-(float) statusBarHeight
{
CGSize statusBarSize = [[UIApplication sharedApplication] statusBarFrame].size;
return MIN(statusBarSize.width, statusBarSize.height);
}
I am updating with #Anbu.Karthic solution.
In your (IBAction)MenuTap:(id)sender update the code with below. It will work. I have tried.
- (IBAction)MenuTap:(id)sender
{
_menuView.hidden = NO;
[self.navigationController.view addSubview:_menuView];
_menuView.frame = [[UIScreen mainScreen] bounds];
}

The navigation bar and bottom toolbar is not working(not respond to tap/click)

I have a problem in ios7(ipad), that is, the navigation bar and the bottom toolbar can not catch the tap event. The same code works fine in the ios 8 (iphone/ipad). Here is my code, I have a slideView which is a UIView, and I push another UIView singleCamView into it. The first time I load into the singleCamView, the navigation and the toolbar isn't working, but when I go back to slideView and get into the singleCamView again, everything is fine.
In slideView:
(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self changeUILayout];
[serverMgr disableTalkFunc];
if (eLayoutType == eLayout_1X1 && !backFrom1x1) {
[self changeLayout_1x1];
}
}
(void)changeLayout_1x1 {
if ([self.navigationController.visibleViewController isKindOfClass:[SlideView class]]) {
int camInArray = 0;//iPageIdx * [self getPreviewNum] + singleCamPos;
SinglePageViewController_Base *firstPage = [viewControllers objectAtIndex:0];
SingleCamViewController * mCam = [[SingleCamViewController alloc] initWithServerManager:serverMgr CurrentCam:camInArray];
[mCam setParent:firstPage];
[mCam setTitle:[serverMgr getDeviceNameByChIndex:0]];
mCam.changeLayoutDelegate = self;
int ch_index = 0;//iPageIdx * [self getPreviewNum] + pos;
[serverMgr updateAudioAndPtzDeviceByChIndex:ch_index];
[mCam setPtzCap:[serverMgr isSupportPTZ:ch_index]];
[mCam setAudioCap:[serverMgr isSupportAudio:ch_index]];
[mCam setTalkCap:[serverMgr isSupportTalk:ch_index]];
[firstPage setSingleCam:mCam];
[serverMgr setPlaybackDelegate:mCam];
[self.navigationController pushViewController:mCam animated:YES];
//clear to default picture
[firstPage setDefaultPic];
[serverMgr disconnectAllCam];
[serverMgr connectToCamWithHighResolution:ch_index];
[mCam release];
eLayoutType = eLayout_1X1;
[serverMgr setLayoutType:eLayout_1X1];
[parent save];
}
else {
return;
}
}
In singleCamView:
....
UIImage *backImage;
UIButton *bButton = [UIButton buttonWithType:UIButtonTypeCustom];
if (IS_IPAD)
backImage = [UIImage imageNamed:#"Back_48x48_nor.png"];
else
backImage = [UIImage imageNamed:#"Back_32x32_nor.png"];
bButton.bounds = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
[bButton setImage:backImage forState:UIControlStateNormal];
[bButton addTarget:self action:#selector(onBackBtnTap) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem * backButton = [[UIBarButtonItem alloc] initWithCustomView:bButton];
UIBarButtonItem * backButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(#"Back", nil) style:UIBarButtonItemStylePlain target:self action:#selector(onBackBtnTap)];
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
[backButton setTintColor:COLOR_NAVBUTTONTINT];
}
else {
[backButton setTintColor:COLOR_NAVBUTTONTINTIOS6];
}
self.navigationItem.leftBarButtonItem = backButton;
[backButton release];
The important thing is, it works fine in ios8, I can't figure out the reason. Thank you.
Finally I solve my own problem, here is the solution, the key point is that the second view is pushed right after the main view is created, the controller (maybe) is not fully initialized yet. So I add a delay between main view and second, everything works fine.
This post gives me the solution. Adding delay between execution of two following lines

Change items in navigation bar on device rotation

I have custom UIBarButton items added to UINavigationBar as rightbarbuttonitems. I add two more items in UIBarButton when device goes to landscape mode. I am getting rotation call and I am correctly removing items from UIBarbuttons array based on device orientation, but my navigationbar item set never gets updates.
If i start with portrait mode, it shows what it suppose to. When I rotate to landscape new items are not added to navigation bar and vice versa extra item won't go when device go to portrait.
I am not sure how I can change navigationbaritems on device rotation. Per me I am doing all things correct.
-(void)setUpOnRotation:(BOOL)toPortrait{
_searchMessage = [[UILabel alloc] initWithFrame:CGRectMake(3.0, 0, 110, 20)];
_searchMessage.numberOfLines = 2;
_searchMessage.textColor = [UIColor blackColor];
_searchMessage.font = [UIFont systemFontOfSize:8.0];
_searchMessage.text = #"";
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 15, 130, 25)];
_searchBar.delegate = self;
_searchBar.showsCancelButton = NO;
UIBarButtonItem* doneButton = [BarButtons doneButtonWithTarget:self action:#selector(cancel)];
UIBarButtonItem *searchActivityItem = [[UIBarButtonItem alloc] initWithCustomView:_searchMessage];
UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:_searchBar];
UIBarButtonItem *in = [BarButtons nativeButtonNamed:#"In"
title:#"In"
target:self
action:#selector(In)];
UIBarButtonItem *out = [BarButtons nativeButtonNamed:#"Out"
title:#"Out"
target:self
action:#selector(Out)];
NSMutableArray *itemsSet;
itemsSet = [NSMutableArray arrayWithObjects:in,
out,
searchItem,
searchActivityItem,
doneButton, nil];
if (toPortrait) {
if ([itemsSet containsObject:searchItem] || [itemsSet containsObject:searchActivityItem]) {
[itemsSet removeObject:searchActivityItem];
[itemsSet removeObject:searchItem];
}
}
[_searchBar release];
[searchItem release];
[_searchActivity release];
[_searchMessage release];
[searchActivityView release];
self.navigationItem.rightBarButtonItems = itemsSet;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[self setUpOnRotation:UIInterfaceOrientationIsPortrait(toInterfaceOrientation)];
} -(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:NO animated:animated];
[self setUpOnRotation:UIInterfaceOrientationIsPortrait(self.interfaceOrientation)];}
Note: setUpOnRotaion method is called from willAnimateRotationToInterfaceOrientation and viewWillAppear with UIInterfaceOrientationIsPortrait(self.intefaceOrientation) and it does give me correct result. I have debugged.
In willAnimateRotationToInterfaceOrientation change cehck for orientation
if([uidevice orientaiton]statusbarorientation]){
self.naviogationite.rightbarbuttonitems = #[btn1,btn2,btn3];
}
else{
self.naviogationite.rightbarbuttonitems = #[abtn1,abtn2,abnt3];
}
u can do like this
can u do like this
NSMutableArray *itemsSet;
if(!toPortrait){
itemsSet = [NSMutableArray arrayWithObjects:in,
out,
searchItem,
searchActivityItem,
doneButton, nil];
}
if (toPortrait) {
itemsSet = [NSMutableArray arrayWithObjects:in,
out,
doneButton, nil];
}

UIView only shows after being called the second time

I have a view controller that is calling a custom UIView via an IBAction.The custom view contains a UIPickerView that slides up from the bottom of the screen and a toolbar with 'cancel' and 'done' buttons above it. The problem is that the view only appears on the screen after being called for the second time. Using breakpoints I can verify that every single line of code is being called both times. Everything seems to be happening the same way each time. Nothing is NIL, and in fact it's like this for the duration that the app is running, not only the first time it's called. You always have to click the button twice to get the view to appear for as long as the app is running.
Admittedly, the code for the custom picker view is not mine. I copied it from someone else's example. I'm not sure if it's the problem or not. I don't see how it could be, but I'm a bit over my head here. This is how I'm calling the view from my view controller.
- (IBAction)statusPickerButtonPressed:(id)sender {
self.scrollPickerView = [[StatusPickerView alloc]init];
[self.navigationController.view addSubview:self.scrollPickerView];
self.scrollPickerView.delegate = self;
self.scrollPickerView.dataSource = self;
}
and here's the custom UIView
#import "StatusPickerView.h"
#interface StatusPickerView ()
#property NSArray *pickerArray;
#property NSInteger selectedRow;
#end
#implementation StatusPickerView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setToolbar];
[self becomeFirstResponder];
float screenWidth = [UIScreen mainScreen].bounds.size.width;
float pickerWidth = screenWidth * 3 / 4;
float xPoint = screenWidth / 2 - pickerWidth / 2;
[self setFrame: CGRectMake(xPoint, 50.0f, pickerWidth, 180.0f)];
self.showsSelectionIndicator = YES;
[self selectRow:3 inComponent:0 animated:YES];
}
return self;
}
-(void)setToolbar
{
_toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[_toolbar setBarStyle:UIBarStyleDefault];
UIBarButtonItem * btnCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:#selector(barbtnPressed:)];
UIBarButtonItem * flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem * btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(barbtnPressed:)];
[btnCancel setTag:1];
[btnCancel setStyle:UIBarButtonItemStyleBordered];
[btnDone setTag:2];
[btnDone setStyle:UIBarButtonItemStyleBordered];
NSArray * btnArray = [[NSArray alloc] initWithObjects:btnCancel, flexible, btnDone, nil];
[_toolbar setItems:btnArray];
self.inputAccessoryView = _toolbar;
self.inputView = self;
}
-(BOOL)canBecomeFirstResponder
{
return true;
}
-(void)barbtnPressed:(id)sender
{
NSInteger tag = [sender tag];
switch (tag) {
case 1:
{
[self removeFromSuperview];
break;
}
case 2:{
[self removeFromSuperview];
self.selectedRow = [self selectedRowInComponent:0];
[[NSNotificationCenter defaultCenter]postNotificationName:#"user_selected_new_section" object:self];
}
default:
break;
}
}
-(int)giveSelectedRow{
return self.selectedRow;
}
I'm fully prepared to feel foolish here, as the solution is probably obvious, just not obvious to myself.
edit:
I tried using [self.view.window addSubview:self.scrollPickerView]; instead of [self.navigationController.view addSubview:self.scrollPickerView];, and the behavior is exactly the same.
This line:
[self.navigationController.view addSubview:self.scrollPickerView];
should read:
[self.view addSubview:self.scrollPickerView];
You’re calling -init instead of -initWithFrame:, so your view is ending up with the default frame of CGRectZero. Considering that you’re then making a frame of your own, that call might as well pass that in to start out with:
self.scrollPickerView = [[ScrollPickerView alloc] initWithFrame:CGRectZero];
Alternatively, you could keep the current self.scrollPickerView = … code and change the -initWithFrame: to an -init, like this:
- (id)init
{
float screenWidth = [UIScreen mainScreen].bounds.size.width;
float pickerWidth = screenWidth * 3 / 4;
float xPoint = screenWidth / 2 - pickerWidth / 2;
self = [super initWithFrame:CGRectMake(xPoint, 50.0f, pickerWidth, 180.0f)];
if (self) {
[self setToolbar];
[self becomeFirstResponder];
self.showsSelectionIndicator = YES;
[self selectRow:3 inComponent:0 animated:YES];
}
return self;
}

Permanet view on window objective c

I need to add a UIView to the main window, the UIView consists in a view with some buttons.
The problem is, the buttons i put inside that view, is not responding for the touch events,
like it have some view in front of it.
That view need to be a singleton class, cause i need to respond the touchevent in any class.
Heres the code for the UIView :
+ (MenuBarView *)sharedMenuBar
{
static MenuBarView *sharedSingleton;
#synchronized(self) {
if (!sharedSingleton) sharedSingleton = [[MenuBarView alloc] init];
return sharedSingleton;
}
}
-(id)init
{
self = [super init];
if(self)
{
self.userInteractionEnabled = YES;
backgroundBarImage = [UIImage imageNamed:#"Barra.png"];
UIImageView * backgroundBar = [[UIImageView alloc]initWithImage:backgroundBarImage];
backgroundBar.contentMode = UIViewContentModeCenter;
backgroundBar.backgroundColor = [UIColor clearColor];
[backgroundBar setFrame:CGRectMake(0, 0, backgroundBarImage.size.width, backgroundBarImage.size.height)];
[self addSubview:backgroundBar];
UIButton * rootBTN = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[rootBTN setFrame:CGRectMake(0, 8, 100, 40)];
[rootBTN addTarget:self action:#selector(selectedBarButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:rootBTN];
UIImage * localizacaoIMG = [UIImage imageNamed:#"Localizador"];
UIImageView * localizacaoView = [[UIImageView alloc]initWithImage:localizacaoIMG];
localizacaoView.contentMode = UIViewContentModeScaleAspectFill;
[localizacaoView setFrame:CGRectMake(backgroundBar.frame.origin.x+130, 8, localizacaoIMG.size.width, localizacaoIMG.size.height)];
[backgroundBar addSubview:localizacaoView];
UIButton * localizacaoBTN = [UIButton buttonWithType:UIButtonTypeCustom];
[localizacaoBTN setFrame:CGRectMake(backgroundBar.frame.origin.x+110, 8, 60, 40)];
localizacaoBTN.tag = 1;
[self addSubview:localizacaoBTN];
}
return self;
}
//The event handling method
-(void)selectedBarButton:(UIButton *)sender
{
NSLog(#"OK");
[self.delegate selectedMenuBar:sender.tag];
}
and heres the implementation on the AppDelegate :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[InitialViewController alloc] init];
self.navController = [[EzMallNavViewController alloc]initWithRootViewController:self.viewController];
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
if(IS_IPOD)
{
[[MenuBarView sharedMenuBar]setFrame:CGRectMake(0, self.window.frame.size.height-51, [MenuBarView sharedMenuBar].frame.size.width, [MenuBarView sharedMenuBar].frame.size.height)];
}
else
{
[[MenuBarView sharedMenuBar]setFrame:CGRectMake(0, self.window.frame.size.height, [MenuBarView sharedMenuBar].frame.size.width, [MenuBarView sharedMenuBar].frame.size.height)];
}
[MenuBarView sharedMenuBar].delegate = self;
[self.window addSubview:[MenuBarView sharedMenuBar]];
return YES;
}
#pragma mark MenuBarDelegateMethods
-(void)selectedMenuBar:(int) tag
{
NSLog(#"Here");
}
It looks like your menu view has a zero size frame so no touches are detected. The buttons appear on screen because the menu view isn't set to clip drawing to its bounds.
Try to set different color for different views and analyze the view hierarchy ,it might be possible that you have added the view in wrong order .

Resources