Button won't log textfield values - ios

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.

Related

ObjectiveC - UIButton remains highlighted/selected and background color and font color changes when highlighted/selected

I have used the interface builder to create the following UIButton for different time slot and a UIButton for Search. I want the UIButton for different time slot to remain selected/highlighted when user tap on it. And the background color and font color will change as well (See pic for illustration). Moreover, user can only select one of the time slot at one time.
UIButton with different time slot
What I am trying to achieve button
Code
#import "Search.h"
#import <QuartzCore/QuartzCore.h>
#interface Search(){
}
#end
#implementation Search
#synthesize btn1;
#synthesize btn2;
#synthesize btn3;
#synthesize btn4;
#synthesize btn5;
#synthesize btn6;
#synthesize btn7;
#synthesize btn8;
#synthesize btn9;
#synthesize btnSearch;
- (void)viewDidLoad
{
[super viewDidLoad];
_borderBox.layer.shadowRadius = 5;
_borderBox.layer.shadowColor = [UIColor colorWithRed:211.f/255.f green:211.f/255.f blue:211.f/255.f alpha:1.f].CGColor;
_borderBox.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
_borderBox.layer.shadowOpacity = 0.9f;
_borderBox.layer.masksToBounds = NO;
btn1.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn1.layer.borderWidth =1.0f;
btn2.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn2.layer.borderWidth =1.0f;
btn3.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn3.layer.borderWidth =1.0f;
btn4.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn4.layer.borderWidth =1.0f;
btn5.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn5.layer.borderWidth =1.0f;
btn6.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn6.layer.borderWidth =1.0f;
btn7.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn7.layer.borderWidth =1.0f;
btn8.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn8.layer.borderWidth =1.0f;
btn9.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn9.layer.borderWidth =1.0f;
}
-(void)viewWillAppear:(BOOL)animated{
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{
CALayer *layer = button.layer;
layer.cornerRadius = 8.0f;
layer.masksToBounds = YES;
layer.borderWidth = 4.0f;
layer.opacity = .3;//
layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;
CAGradientLayer *colorLayer = [CAGradientLayer layer];
colorLayer.cornerRadius = 8.0f;
colorLayer.frame = button.layer.bounds;
//set gradient colors
colorLayer.colors = [NSArray arrayWithObjects:
(id) color.CGColor,
(id) color.CGColor,
nil];
//set gradient locations
colorLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f],
nil];
[button.layer addSublayer:colorLayer];
}
Theoretically, you could do the following:
Store all the buttons in an array (an instance variable)
Add a target to each button which sets one button to be selected and deselects all other buttons.
The constructor function of the button would like something like this:
-(UIButton *)newButtonWithTitle:(NSString *)title fontSize:(NSInteger)fontSize {
UIColor *selectedButtonColor = [UIColor colorWithRed:1.0 green:0.2 blue:0.2
alpha:0.5];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:selectedButtonColor forState:UIControlStateHighlighted];
[button setTitleColor:selectedButtonColor forState:UIControlStateSelected];
button.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
button.layer.borderColor = [UIColor lightGrayColor].CGColor;
button.layer.borderWidth = 1.0;
[button addTarget:self action:#selector(scheduleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
The button action function could be:
-(void)scheduleButtonAction:(UIButton *)button {
button.selected = YES;
[self.buttons enumerateObjectsUsingBlock:^(UIButton *aButton, NSUInteger idx, BOOL * _Nonnull stop) {
if (![aButton isEqual:button]) {
aButton.selected = NO;
}
}];
}
BUT I wouldn't do it this way. The problem with this solution is while it is possible, it's not the Apple way and it's definitely not an elegant solution.
There are multiple problems here:
How are you binding the data between each button and the value that it represents? You could do that by either using associative objects OR by subclassing UIButton and adding a property OR by using tags and a lookup table. All of which are not great solutions.
This design is hardcoded and not flexible. There is a lot of boilerplate code for the creation of the buttons and you have to keep track of all these properties.
What are you going to do if the requirement will change and you'll need a button for each hour of the day?
A better way to do this layout, which was hinted by user10277996 is to use a collection view. It will allow you to separate the concerns:
a data source where you decide how many buttons (cells) should be
created (and what data they should contain)
a constructor class for the cell, where you define the design once.
a layout class where you define how to lay out your buttons.
You should take a day or two and get really familiar with UICollectionView as it is one of the most powerful and useful classes in iOS.
Here is a tutorial to get you started:
https://www.raywenderlich.com/975-uicollectionview-tutorial-getting-started
Apple's official documentation:
https://developer.apple.com/library/archive/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40012334-CH1-SW1
If you want to dig deeper, check out the following resources (although not necessary for solving your specific issue):
https://www.objc.io/issues/3-views/collection-view-layouts/
https://ashfurrow.com/uicollectionview-the-complete-guide/
I was able to achieve the function you are working on and below is how i did it.
I created the design via storyboard and connected all the 9 button's actions methods to a single Selector method, inside the action method with the help sender parameter we can get the selected buttons reference and use it.
- (IBAction)btnPressed:(UIButton*)sender {
/* Below for loop works as a reset for setting the default colour of button and to not select the same one twice*/
for (UIButton* button in buttons) {
[button setSelected:NO];
[button setBackgroundColor:[UIColor whiteColor]];
[button setUserInteractionEnabled:true];
// [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
}
NSInteger tag = sender.tag; // Here we get the sender tag, which we can use for our needs. Also we can directly use the sender and get the title or whatsoever needed.
/*Now below line works as a toggle for the button where multiple buttons can't be selected at the same time.*/
sender.selected = ! sender.selected;
if(sender.selected)
{
/* Here we set the color for the button and handle the selected function*/
[sender setSelected:YES];
[sender setUserInteractionEnabled:false];
[sender setBackgroundColor:[UIColor magentaColor]];
}
}
You can also add custom layer for the button by using the "sender.Layer" property.
The Whole code is added below,
All the button's action needs to be connected to a single selector method,
- (IBAction)btnPressed:(UIButton*)sender;
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UIView *mainViewOL;
#property (weak, nonatomic) IBOutlet UIButton *btn1;
#property (weak, nonatomic) IBOutlet UIButton *btn2;
#property (weak, nonatomic) IBOutlet UIButton *btn3;
#property (weak, nonatomic) IBOutlet UIButton *btn4;
#property (weak, nonatomic) IBOutlet UIButton *btn5;
#property (weak, nonatomic) IBOutlet UIButton *btn6;
#property (weak, nonatomic) IBOutlet UIButton *btn7;
#property (weak, nonatomic) IBOutlet UIButton *btn8;
#property (weak, nonatomic) IBOutlet UIButton *btn9;
#end
#implementation ViewController
NSArray* buttons;
- (void)viewDidLoad {
[super viewDidLoad];
buttons = [NSArray arrayWithObjects:_btn1, _btn2, _btn3,_btn4,_btn5,_btn6,_btn7,_btn8,_btn9,nil];
self.mainViewOL.layer.shadowRadius = 5;
self.mainViewOL.layer.shadowColor = [UIColor colorWithRed:211.f/255.f green:211.f/255.f blue:211.f/255.f alpha:1.f].CGColor;
self.mainViewOL.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
self.mainViewOL.layer.shadowOpacity = 0.9f;
self.mainViewOL.layer.masksToBounds = NO;
/* I Have added the 9 button's in an array and used it to reduce the lines of code and for easy understanding as well*/
for (UIButton* button in buttons) {
button.layer.borderColor = [UIColor lightGrayColor].CGColor;
button.layer.borderWidth =1.0f;
}
}
- (IBAction)btnPressed:(UIButton*)sender {
for (UIButton* button in buttons) {
[button setSelected:NO];
[button setBackgroundColor:[UIColor whiteColor]];
[button setUserInteractionEnabled:true];
// [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; //Based on your needs and colour variant you cant add properties to the button for different control states.
[button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
}
NSInteger tag = sender.tag;
sender.selected = ! sender.selected;
if(sender.selected)
{
[sender setSelected:YES];
[sender setUserInteractionEnabled:false];
[sender setBackgroundColor:[UIColor purpleColor]];
sender.backgroundColor = [UIColor magentaColor];
}
}
#end
And the Final Result
Ignore the delay in button selection, it is caused by the video to gif conversion.
Hope This helps.
Try to use custom type button.
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
Or set this property in Interface Builder.
You can prepare you screen with the help UICollectionView.
Create custom class with UICollectionViewCell and override below property.
override var isSelected: Bool `{
willSet{
super.isSelected = newValue
// put button background color value as per selected state`
You can get any button and control any button through the tag control.

UIButton as a subview not responding

I have a UIButton inside of a UIView inside of a UIImageView that is not responding to touches. I can't figure out why. I've broken the code down to its simplest form while still doing what my original program does.
#import "TestVideoViewController.h"
#interface TestVideoViewController ()
#property (strong, nonatomic)UIImageView *panel;
#property (strong, nonatomic)UIView *panelSC;
#property (strong, nonatomic)UIButton *panelButtonSC;
#property (strong, nonatomic)UIButton *videoButton;
#end
#implementation TestVideoViewController
-(void) viewDidLoad {
_panelButtonSC = [UIButton buttonWithType:UIButtonTypeCustom];
[_panelButtonSC addTarget:self action:#selector(buttonPressedSC:) forControlEvents:UIControlEventTouchUpInside];
[_panelButtonSC setTitle:#"Open" forState:UIControlStateNormal];
_panelButtonSC.frame = CGRectMake(511, 701, 66, 67);
_panel = [[UIImageView alloc] initWithFrame:CGRectMake(100, 768, 824, 600)];
_panel.backgroundColor = [UIColor whiteColor];
_panelSC = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 784, 560)];
_panelSC.backgroundColor = [UIColor whiteColor];
_videoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_videoButton addTarget:self action:#selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
[_videoButton setTitle:#"Play" forState:UIControlStateNormal];
[_videoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_videoButton.frame = CGRectMake(400, 400, 200, 40);
[_panelSC addSubview:_videoButton];
[_panel addSubview:_panelSC];
[self.view addSubview:_panel];
[self.view addSubview:_panelButtonSC];
}
- (IBAction)buttonPressedSC:(UIButton*)sender {
[self animatePanelUp];
}
- (IBAction)playVideo:(UIButton*)sender {
NSLog(#"play video");
}
- (void) animatePanelUp {
[UIView animateWithDuration: 0.5
delay: 0.0
options: UIViewAnimationOptionCurveEaseIn
animations:^{
_panel.frame = CGRectMake(47, 166, 929, 602);
}
completion:nil];
}
#end
I've looked at every similar answer here. To the best of my knowledge all of my framing is correct. There has got to be something simple and stupid that I'm missing. Why doesn't the "playVideo" method ever fire? The only time it works is if I add the button directly to self.view.
UIImageView keeps userInteractionEnabled as false by default - add following line of code it will work.
_panel.userInteractionEnabled = true;
As you are adding a few subview upon one another, check that your button is clickable and no other subview is eating up the touch event, and overall make sure that your views are user action enabled.
Hint:
There might have some problem with the imageview used, as it will have user interaction disabled by default.
Use UIView instead or do this:
_panelSC.userInteractionEnabled = true;
Make sure user interaction is enabled of the parent view. UIImageView by default has userInteractionEnabled false.
_panel.userInteractionEnabled = true

How to create gmail recipient format in iOS?

I need to create a view like below from the array of emails that I receive which also has the delete option.
Something similar to that of gmail's mail recipient except in my this should be scrollview. My main issue is to create the background with delete button which stretches based on the email length. My current approach is to use 3 images one for the beginning, one for the end with delete button and one in general for middle that will stretch. Is there any other or better way to do this?
NOTE:Need to support from iOS 5 and above
Here you go, I have created a SuperLabel for you though it might need some tweak.. But it will help you for sure..
SuperLabel.h
#import <UIKit/UIKit.h>
#interface SuperLabel : UIView
- (id)initWithFrame:(CGRect)frame andTitle:(NSString *)title;
#end
SuperLabel.m
#import "SuperLabel.h"
#define MAX_HEIGHT 25.0
#implementation SuperLabel
- (id)initWithFrame:(CGRect)frame andTitle:(NSString *)title
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
//Design your label view
self.backgroundColor=[UIColor colorWithRed:.8 green:.8 blue:.8 alpha:1.0];
self.layer.borderColor=[[UIColor orangeColor] CGColor];
self.layer.borderWidth=1.0;
self.layer.cornerRadius=5.0;
//Add a Label
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(5.0, 5.0, 100.0, MAX_HEIGHT)];
label.font=[UIFont systemFontOfSize:12.0];
label.textColor=[UIColor grayColor];
label.text=title;
[label sizeToFit];
[self addSubview:label];
//We will get resized frame after using sizeToFit after setting the text in the label.
CGRect rect=label.frame;
//Add a button
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:#"x" forState:UIControlStateNormal];
btn.titleLabel.font=[UIFont systemFontOfSize:12.0];
btn.titleLabel.textColor=[UIColor grayColor];
rect.origin.x=rect.origin.x+rect.size.width;
rect.origin.y=0;
rect.size=CGSizeMake(25.0, MAX_HEIGHT);
[self addSubview:btn];
[btn addTarget:self action:#selector(deleteMe:) forControlEvents:UIControlEventTouchDragInside];
btn.frame=rect;
//Change the whole frame of the label view
frame.size.height=MAX_HEIGHT;
frame.size.width=btn.frame.origin.x+btn.frame.size.width;
self.frame=frame;
}
return self;
}
-(IBAction)deleteMe:(id)sender{
[self removeFromSuperview];
}
#end
And finally add to your view by using following code..
SuperLabel *label=[[SuperLabel alloc] initWithFrame:CGRectZero andTitle:#"myemail#gmail.com"];
[self.view addSubview:label];
Cheers..

iOS - Implementing a Class for UITextField

I have a UIView, with lots of UITexfields,
UITextField *field1 = [[UITextField alloc] initWithFrame:CGRectMake(135, 292, 50, 20)];
field1.backgroundColor = [UIColor clearColor];
field1.borderStyle = UITextBorderStyleNone;
field1.returnKeyType = UIReturnKeyNext;
field1.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
field1.font = [UIFont fontWithName:inputFont size:fontSize];
field1.placeholder = #"size";
[self addSubview:field1];
Can I create a UITextField Class and create an instance of this class with these parameters preset? -so as to reduce the code: (If I have lots of fields the code gets very long and repetitive? -
Can i get some help on how about to set up this class! -thank you
Yes You Can do this by making a BaseUITextFeild .h and .m file as shown in the following image.
And then Just add the following code regarding your design in BaseUITextFeild.m file
- (void)awakeFromNib {
[self setupUI];
[self setKeyboardAppearance:UIKeyboardAppearanceAlert];
}
// Function to setup the common UI throught the app.
- (void)setupUI {
[self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[self setTextAlignment:NSTextAlignmentCenter];
[self setValue:[UIColor colorWithRed:120.0/225.0 green:120.0/225.0 blue:120.0/225.0 alpha:1.0] forKeyPath:#"_placeholderLabel.textColor"];
[self setFont:[UIFont boldSystemFontOfSize:15.0f]];
}
Generating a custom UITextField programmatically
And then just import "BaseUITextFeild.h" in the ViewController Where you want to use it.
BaseUITextFeild *field1 = [[BaseUITextFeild alloc] initWithFrame:CGRectMake(135, 292, 50, 20)];
[self addSubview:field1];
Generating a custom UITextField From Interface Builder(Storyboard/.XIB)
Add a UITextfield and then just Change the Class to your Custom TextView Class.
By Applying Following technique you can use this same UITextFeild through out the Application, Just need to import BaseUITextFeild.h.
You can also use this UITextFieldCategory
Follow this Two Example UITextField+withFrame.h and UITextField+ColoredPlaceholder.h.
You can also customize you UITextField as per your need.
Create a method
-(UITextField*)createTextFieldWithFrame:(CGRect)frame{
UITextField *textField = [[UITextField alloc] initWithFrame:frame];
textField.backgroundColor = [UIColor clearColor];
textField.borderStyle = UITextBorderStyleNone;
textField.returnKeyType = UIReturnKeyNext;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
textField.placeholder = #"size";
[self.view addSubview:textField];
return textField;
}
for creating multiple textfields call this method
UITextField *text1 = [self createTextFieldWithFrame:CGRectZero];
UITextField *text2 = [self createTextFieldWithFrame:CGRectZero];
You can create a custom xib with the UITextField created as you want and reuse that every time you need.
Or you can subclass UITextField and do the additional setup inside.

Adding Items to UIToolbar Programmatically Not Working

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];

Resources