I recently have been asking questions pertaining to UIToolbars and what not, but now I discover I need to add items to it programatically, I have seen other people's methods on how to go about doing it, but when I try doing the same thing, nothing ends up appearing. Pinpointing this problem is what I need help with. Here are my connections in IB:
And here is the relevant code:
Header file:
#import <UIKit/UIKit.h>
#interface ParkingRootViewController : UIViewController {
UINavigationController *navigationController;
UIToolbar *toolbar;
UIBarButtonItem *lastUpdateLabel;
}
#property(nonatomic, retain) IBOutlet UINavigationController *navigationController;
#property (nonatomic, retain) IBOutlet UIToolbar *toolbar;
#property (nonatomic, retain) IBOutlet UIBarButtonItem *lastUpdateLabel;
- (IBAction)selectHome:(id)sender;
#end
Implementation file:
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 150.0f, 20.0f)];
label.text = #"last updated...";
label.textColor = [UIColor colorWithWhite:1.0 alpha:1.0];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
label.font = [UIFont boldSystemFontOfSize:13.0];
label.userInteractionEnabled = NO;
lastUpdateLabel = [[UIBarButtonItem alloc] initWithCustomView:label];
[label release];
[toolbar setItems:[NSArray arrayWithObject:lastUpdateLabel]];
[self.view addSubview:self.navigationController.view];
//[self.view addSubview:toolbar];
//[self.navigationController.view addSubview:toolbar];
[self.navigationController.view setFrame:self.view.frame];
}
Any help is greatly appreciated!
EDIT:
I removed whatever I had in the nib which would cause the toolbar to appear/be modified and I updated my code in viewDidLoad to the following:
self.navigationController.toolbarHidden = NO;
//creating label in tool bar
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 150.0f, 20.0f)];
label.text = #"last updated...";
label.textColor = [UIColor colorWithWhite:1.0 alpha:1.0];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
//label.highlightedTextColor = [UIColor colorWithWhite:0.5 alpha:1.0];
//label.highlighted = YES;
label.font = [UIFont systemFontOfSize:13.0];
label.userInteractionEnabled = NO;
UIBarButtonItem *lastUpdateLabel = [[UIBarButtonItem alloc] initWithCustomView:label];
//[lastUpdateLabel initWithCustomView:label];
//[label release];
//[toolbar setItems:[NSArray arrayWithObject:lastUpdateLabel]];
[self setToolbarItems:[NSArray arrayWithObject:lastUpdateLabel]];
And I end up getting a blank toolbar showing up. I fire up the debugger and this is what I see:
Aha! lastUpdateLabel's view's _text field is out of scope! But why? And how would I remedy this?
EDIT 2:
I have been able to add labels and an NSActivityIndicator with the following code:
#synthesize refreshDataButton;
//...
self.navigationController.toolbarHidden = NO;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 0.0f, 80.0f, 40.0f)];
label.text = #"last updated...";
label.textColor = [UIColor colorWithWhite:1.0 alpha:1.0];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
label.font = [UIFont systemFontOfSize:13.0];
label.userInteractionEnabled = NO;
[self.toolbar addSubview:label];
// create activity indicator
// dist frm lft, dist frm top
CGRect frame = CGRectMake( 90.0, 11.0, 25.0, 25.0);
UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc] initWithFrame:frame];
loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
[loading sizeToFit];
loading.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin);
[loading startAnimating];
[self.toolbar addSubview:loading];
But when I try to add a UIBarButtonItem I have no luck (doesn't show up in the toolbar):
self.refreshDataButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:100 target:self action:#selector(refreshDataButtonTapped)];
[self setToolbarItems:[NSArray arrayWithObject:refreshDataButton]];
Here is the header file:
#import <UIKit/UIKit.h>
//#import <CoreData/CoreData.h>
#interface ParkingRootViewController : UIViewController {
UINavigationController *navigationController;
UIToolbar *toolbar;
UIBarButtonItem *refreshDataButton;
//UIActivityIndicatorView *loading;
}
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#property (nonatomic, retain) IBOutlet UIToolbar *toolbar;
#property (nonatomic, retain) UIBarButtonItem *refreshDataButton;
//#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *loading;
#property (nonatomic, readonly) NSString *applicationDocumentsDirectory;
-(IBAction)selectHome:(id)sender;
-(void)testCoreData;
-(void)refreshDataButtonTapped;
#end
The code should work...there are couple of suggestions I could make. Instead of:
[toolbar setItems:[NSArray arrayWithObject:lastUpdateLabel]];
try this:
[toolbar setItems:[NSArray arrayWithObject:lastUpdateLabel] animated:YES];
Also, since you are using a UINavigationController, NavControllers come with their own toolbar that you could use if you like. By default it is hidden, which you can make visible by doing this:
self.navigationController.toolbarHidden = NO;
and you can set its toolbar items by doing this:
[self setToolbarItems:[NSArray arrayWithObject:lastUpdateLabel]];
Hope this tid bit helps you. good luck!
The buttons need to be added by the viewController that is pushed by the navigationController. The navController holds the bar, but the items on the bar are controlled (added) by the viewController that is being shown. That way, each different kind of vc has it's own bar.
So take that barbuttonitem code, and plunk it in the init section of the vc, and enjoy.
//try this one.
- (void)viewDidAppear:(BOOL)animated
{
[toolbar setItems:[NSArray arrayWithObject:lastUpdateLabel]];
}
The code posted works fine, I think it has to be how the XIB is hooked up. I would re-do your connections in IB (ie break all the connections and re make them), save your XIB and try again.
You can add label to tool bar directly if u have instantiated it with frame...for example
UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(7,7,200,30)];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setText:#"Test lbl"];
[_toolBar addSubview:lbl];
Related
I have a weird bug which only happens in iPhone 6 simulator in Xcode 6. I have a generic component which extends UITextField and shows a pickerView as inputView at the bottom of screen.
If I use iPhone5 or iPhone5s to test my application, it's working as expected: inputView and inputAccessoryView is displaying correctly. But if I switch to iPhone 6 or Plus simulator, only inputAccessoryView is shown at bottom of screen, inputView is not showing.
Here is my code:
#interface DropDownTextField : UITextField
#property (strong,nonatomic) UIPickerView* pickerView;
#property (strong,nonatomic) UIToolbar *toolBar;
#property CGFloat originalFontSize;
#property (nonatomic) id<UIPickerViewDelegate> pickerDelegate;
#property (nonatomic) id<UIPickerViewDataSource> pickerDataSource;
- (CGFloat)requiredFontSize;
- (void)setDropdownMode:(BOOL)enabled;
#end
#implementation DropDownTextField
-(id)initWithCoder:(NSCoder *)aDecoder {
if(self = [super initWithCoder:aDecoder]) {
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
[self setFont:[UIFont mediumRegular]];
_originalFontSize = self.font.pointSize;
self.layer.borderWidth = 1.0f;
CGRect frame = [self frame];
// rightview dropdown arrow
UIImageView *dropDownImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (frame.size.height-8)/2, 14.0f, 8.0f)];
UIImage *dropDownImage = [UIImage imageNamed:#"DisclosureDown"];
[dropDownImageView setImage:dropDownImage];
dropDownImageView.contentMode = UIViewContentModeScaleAspectFit;
UIView *dropDownView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25.0f, frame.size.height)];
[dropDownView addSubview:dropDownImageView];
self.rightView = dropDownView;
self.rightViewMode = UITextFieldViewModeAlways;
[self.rightView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(becomeFirstResponder)]];
// picker view
_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,216)];
_pickerView.showsSelectionIndicator = YES;
[_pickerView setBackgroundColor:[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f]];
self.inputView = _pickerView;
// picker view toolbar
_toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,44)];
[_toolBar setBackgroundColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0f]];
[_toolBar setBarStyle:UIBarStyleBlackTranslucent];
// to align button to the right
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] init];
[barButtonDone setTarget:self];
[barButtonDone setAction:#selector(changeSelectionFromLabel:)];
[barButtonDone setTitle:NSLocalizedString(#"ok", #"")];
[barButtonDone setTintColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0f]];
[barButtonDone setStyle:UIBarButtonItemStylePlain];
[barButtonDone setTitleTextAttributes:[UIFont pickerTitleTextAttributes] forState:UIControlStateNormal];
UIBarButtonItem *barButtonCancel = [[UIBarButtonItem alloc] init];
[barButtonCancel setTarget:self];
[barButtonCancel setAction:#selector(dismissPickerView:)];
[barButtonCancel setTitle:NSLocalizedString(#"cancel", #"")];
[barButtonCancel setTintColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0f]];
[barButtonCancel setStyle:UIBarButtonItemStylePlain];
[barButtonCancel setTitleTextAttributes:[UIFont pickerTitleTextAttributes] forState:UIControlStateNormal];
self.toolBar.items = [[NSArray alloc] initWithObjects:barButtonCancel,flex,barButtonDone,nil];
self.inputAccessoryView = _toolBar;
}
return self;
}
Does anybody come across such a problem? Any ideas to resolve?
PS: I've already tried clearing build directory, clean/rebuild project, stop/restart simulator and xcode approaches. Not working.
try to uncheck simulator -> hardware -> keyboard - > connect hardware keyboard
So for my iOS app, if I delete the textfields and the code which grabs the text field values, the button works--in that it presents the indicated view controller..
But when I add these textfields and try to get the button to also Log their values, the button no longer works in that I push the button and nothing happens.
It's also worth mentioning that the code which creates these textfields is littered with "local declaration of "X" hides instance variable" warnings.. but i hear that's not too important (?)
Here's what's in the .h file:
#interface RootViewController : UIViewController
#property (nonatomic, retain) IBOutlet UITextField *usernameTextfield;
#property (nonatomic, retain) IBOutlet UITextField *passwordTextfield;
- (IBAction)buttonClicked: (id)sender;
#end
And in the .m file:
#import "RootViewController.h"
#import "chooseFeedItemViewController.h"
#interface RootViewController ()
#end
#implementation RootViewController
#synthesize passwordTextfield;
#synthesize usernameTextfield;
- (void)viewDidLoad {
[super viewDidLoad];
UIView* v = self.view;
v.backgroundColor = [UIColor whiteColor];
//load Feed View button
CGRect buttonFrame = CGRectMake(177, 250, 100, 100);
UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
[button setTitle: #"submit" forState: UIControlStateNormal];
[button setTitleColor: [UIColor blueColor] forState: UIControlStateNormal];
[button addTarget: self
action: #selector(buttonClicked:)
forControlEvents: UIControlEventTouchDown];
[v addSubview: button];
//username textfield
IBOutlet UITextField *usernameTextfield = [[UITextField alloc] initWithFrame:CGRectMake(45, 30, 200, 40)];
usernameTextfield.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
usernameTextfield.font = [UIFont fontWithName:#"Helvetica-Bold" size:25];
usernameTextfield.backgroundColor=[UIColor whiteColor];
usernameTextfield.placeholder=#"create username";
//password textfield
IBOutlet UITextField *passwordTextfield = [[UITextField alloc] initWithFrame:CGRectMake(45, usernameTextfield.frame.origin.y+75, 200, 40)];
passwordTextfield.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
passwordTextfield.font = [UIFont fontWithName:#"Helvetica-Bold" size:25];
passwordTextfield.backgroundColor=[UIColor clearColor];
passwordTextfield.placeholder=#"create password";
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(15, 80, 400, 400)];
[view addSubview:usernameTextfield];
[view addSubview:passwordTextfield];
[v addSubview:view];
}
-(IBAction) buttonClicked:(id)sender {
NSString *password = [passwordTextfield text];
NSString *username = [usernameTextfield text];
NSLog(#"username = %# and password = %#", username, password);
[self presentViewController:[ChooseFeedItemViewController new]
animated:YES completion:nil];
}
There's more to the .m file but it's irrelevant, i think
alloc init give you brand spanking new objects, NOT references to your existing ones. Use self.usernameTextField to access your existing object.
You are in completely over your head.
Do not create new text fields. Set up your text fields in Interface Builder (IB), and control-drag from your IB fields into the header of your program to create IBOutlets. Then use those IBOutlets in your code.
It does matter, and matter a great deal, that you are getting "local declaration of "X" hides instance variable" warnings.
The problem is that you have instance variables for your text fields, and then you have code that creates an unrelated set of text fields and installs them in your form. If you also created text fields in IB, then you've got duplicates of each text field, but only one is connected to your IBOutlet instance variables. If you never created the text fields in IB, then your outlets point to nil.
You should stop, find a good book or set of video tutorials on Objective C and/or iOS development, and go through the exercises to learn the basics. Your lack of understanding is more than a few forum questions is going to fix.
I created a view to show in MapView annotation callout.
If I didn't use xib and instantiate this view with initWithFrame, then there is no problem.
But if I use xib, size shown on map is bigger, than is should be.
Code in view:
#interface CalloutContentView : UIView
#property (nonatomic) Visit *visit;
+ (id)customView;
#end
#import "CalloutContentView.h"
#interface CalloutContentView ()
#property (weak, nonatomic) IBOutlet UILabel *title;
#property (weak, nonatomic) IBOutlet UILabel *subtitle;
#property (weak, nonatomic) IBOutlet UISegmentedControl *sc;
#end
#implementation CalloutContentView
+ (id)customView
{
CalloutContentView *customView = [[[NSBundle mainBundle] loadNibNamed:#"CalloutContentView" owner:self options:nil] lastObject];
if ([customView isKindOfClass:[CalloutContentView class]])
return customView;
else
return nil;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// _title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, w, 18)];
_title.font = [UIFont boldSystemFontOfSize:15.0];
// _title.textAlignment = NSTextAlignmentLeft;
_title.textColor = [UIColor colorWithWhite:0.199 alpha:1.000];
_title.numberOfLines = 1;
_title.backgroundColor = [UIColor yellowColor];
[self addSubview:_title];
// _subtitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 25.0, w, 14)];
_subtitle.font = [UIFont systemFontOfSize:12.0];
_subtitle.textAlignment = NSTextAlignmentLeft;
_subtitle.textColor = [UIColor colorWithWhite:0.239 alpha:1.000];
_subtitle.backgroundColor = [UIColor clearColor];
[self addSubview:_subtitle];
// _sc = [[UISegmentedControl alloc]initWithItems:#[#"One",#"Two"]];
_sc.frame = CGRectMake(0, self.frame.size.height - 30, w, 30);
[_sc addTarget:self action:#selector(segmentedControlValueDidChange:) forControlEvents:UIControlEventValueChanged];
[self addSubview:_sc];
}
return self;
}
# end
And in MapViewController:
- (void)popupMapCalloutView {
// Change this for creating your Callout View
CalloutContentView *customView = [CalloutContentView customView];
// CalloutContentView *customView = [[CalloutContentView alloc]initWithFrame: CGRectMake(0, 0, 10, 90)];
// if you provide a custom view for the callout content, the title and subtitle will not be displayed
_calloutView.contentView = customView;
VisitAnnotationView *bottomPin = _visitAnnotationViews[_idAnn];
bottomPin.calloutView = _calloutView;
[_calloutView presentCalloutFromRect:bottomPin.bounds
inView:bottomPin
constrainedToView:_mapView
permittedArrowDirections:SMCalloutArrowDirectionAny
animated:YES];
}
That's how it look like when xib is used:
I am Using UItableView controller , i am not able to add searchbar to navigation bar . i want searchbar to come when search button on navigation bar is clicked. How to add search button and search bar on navigation bar .
add this at button click => .m file:
UISearchBar *sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,10,self.navigationController.navigationBar.bounds.size.width,self.navigationController.navigationBar.bounds.size.height/2)];
sBar.delegate = self;
[self.navigationController.navigationBar addSubview:sBar];
and add this => .h file
#interface ViewController : UIViewController<UISearchBarDelegate>
to make searchbar like this you want to insert Button in Navigation bar controller and set background image as search.png(your image). so, when user click on this button set target as searchbarwill be open. please check below code for your reference.
First of all set delegate method in you .h file.
#interface FriendsViewController : UIViewController <UISearchDisplayDelegate,UISearchBarDelegate,UIAlertViewDelegate>
#property (nonatomic, strong) UIButton *searchButton;
#property (nonatomic, strong) UIBarButtonItem *searchItem;
#property (nonatomic, strong) UISearchBar *searchBar;
#property (strong, nonatomic) UISearchController *searchController;
#property (strong, nonatomic) UISearchDisplayController *d1;
then Insert button in your nevigationbar.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(279,9,25, 25)];
[btn setImage:[UIImage imageNamed:#"search"] //put here your searchimage
forState:UIControlStateNormal];
[btn setTitle:#"" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(clickme:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barbtn=[[UIBarButtonItem alloc]initWithCustomView:btn];
self.tabBarController.navigationItem.rightBarButtonItem=barbtn;
[self.tabBarController.navigationController.navigationBar setHidden:NO];
Now you have to set searchcontroller on clickme your button method.
- (IBAction)clickme:(id)sender{
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 300, 44.0)];
searchBar.autoresizingMask =0;
searchBar.delegate = self;
searchBar.placeholder = #"Search for items...";
searchBar.showsScopeBar=YES;
UIView *searchBarWrapper = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
searchBarWrapper.autoresizingMask = 0;
[searchBarWrapper addSubview:searchBar];
self.searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchBarWrapper];
self.tabBarController.navigationItem.leftBarButtonItem = self.searchItem;
self.navigationItem.rightBarButtonItem = nil;
self.navigationItem.titleView = nil;
////////////// ~ Search Display Controller as Object ~/////////////////////////////
self.d1 = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.d1.delegate = self;
self.d1.searchResultsDataSource = self;
self.d1.searchResultsDelegate = self;
self.d1.searchResultsTableView.rowHeight = 40;
self.d1.displaysSearchBarInNavigationBar = YES;
self.searchBar.translucent = NO;
self.searchBar.barTintColor = [UIColor grayColor];
self.d1.searchBar.tintColor = [UIColor blueColor];
[searchBar sizeToFit];
}
when you click on search icon
For search button you can use UIBarButtonSystemItemSearch if need.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
target:self
action:#selector(actionSearch:)];
and you can set searchbar as title view of navigationbar
self.navigationItem.titleView = mySearchBar;
I wanted to use the bounds of a UIView to create a UILabel and add it to that UIView inside the viewDidLoad method, however, I have found that the bounds of UIView is still null inside viewDidLoad. But when I look at a demo app, the bounds of its UIView is already initialised in viewDidLoad.
In the interface I have
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIView *promotionView;
#end
And I am trying to do
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *container = [[UIView alloc] initWithFrame:self.promotionView.bounds];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, container.bounds.size.height-100, 320, 20)];
label.text = #"Promotion Title";
[container addSubview:label];
[self.promotionView addSubview: container];
}
but it doesn't work because the bounds of promotionView is null.
You can do it like this in viewDidAppear:
-(void)viewDidAppear:(BOOL)animated {
static int first = 1;
if (first) {
UIView *container = [[UIView alloc] initWithFrame:self.promotionView.bounds];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, container.bounds.size.height-100, 320, 20)];
label.text = #"Promotion Title";
[container addSubview:label];
[self.promotionView addSubview: container];
first = 0;
}
}