When I input the following code, the textfields I added are not being displayed in the scrollview:
.h
#interface FirstViewController : UIViewController <UIScrollViewDelegate>
#property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
#property (strong, nonatomic) UITextField *firstField;
#property (strong, nonatomic) UITextField *secondField;
#property (strong, nonatomic) UITextField *thirdField;
.m (viewDidLoad)
self.firstField.placeholder = #"First";
self.firstField.textAlignment = NSTextAlignmentCenter;
self.firstField.font = [UIFont fontWithName:#"Helvetica Neue Light" size:50.0];
self.secondField.placeholder = #"Second";
self.secondField.textAlignment = NSTextAlignmentCenter;
self.secondField.font = [UIFont fontWithName:#"Helvetica Neue Light" size:50.0];
self.thirdField.placeholder = #"Third";
self.thirdField.textAlignment = NSTextAlignmentCenter;
self.thirdField.font = [UIFont fontWithName:#"Helvetica Neue Light" size:50.0];
[self.scrollView addSubview:self.firstField];
[self.firstField autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeRight];
[self.firstField autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.scrollView];
[self.firstField autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.scrollView];
[self.scrollView addSubview:self.secondField];
[self.secondField autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.firstField];
[self.secondField autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.scrollView];
[self.secondField autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.scrollView];
[self.scrollView addSubview:self.thirdField];
[self.thirdField autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.secondField];
[self.thirdField autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeLeft];
[self.thirdField autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.scrollView];
[self.thirdField autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.scrollView];
self.automaticallyAdjustsScrollViewInsets = NO;
I have self.scrollView is within a scrollView by the way (in a pageviewcontroller). I am using PureLayout to position the text fields, and I'm pretty sure the way I did it is correct. Is there something I'm missing?
yes you are missing some code,if you wan't to add UITextField programmatically you must to set size and position on you're view, something like that:
self.firstField.frame = CGRectMake(10, 200, 300, 40);
I hope this will help you.
AutoLayout work slightly differently with UIScrollView: It relate to its contentView instead of its frame. This is explained here.
You will need to set your UIScrollView's contentView property since its CGSizeZero by default. Then if you want your 3 UITextfields to appear side by side, you'll have to change their width constraint because otherwise they will fill the whole contentSize.
Related
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.
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'm trying to add an editable text block to a UIScrollView (so the text blocks scroll when the keyboard shows up) which buttons can change. The problem is creating the UITextView programmatically and adding it to the UIScrollView's subview prevents buttons from being able to access the UITextView.text. So I added the UITextView in the ScrollView in the storyboard, but then the UITextView is autoresized to 1 character since it starts with no text. I've tried using a CGRectMake, but the UITextView won't keep the width fixed. The user won't be able to see their texting with just 1 character visible at a time.
Suggestions on how to have a fixed width, editable textView, added to a scrollView so the keyboard can show, which doesn't automatically resize?
Here is my code:
#interface InventoryViewController ()
#property (weak, nonatomic) IBOutlet UITextField *textTitle;
#end
#implementation InventoryViewController
#synthesize textTitle;
-(void) createViewwithTitle {
UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 400.0f)];
whiteView.backgroundColor = [UIColor redColor];
CGSize containerSize = CGSizeMake(320.0f, 400.0f);
self.containerView = [[UIView alloc] initWithFrame:(CGRect) {.origin = CGPointMake(0.0f, 0.0f), .size=containerSize}];
[self.scrollView setDelegate:self];
[self.scrollView addSubview:self.containerView];
postion = CGRectMake(122.0f, 34.0f, 178.0f, 30.0f);
[textTitle setTextColor:[UIColor blackColor]];
[textTitle setBorderStyle:UITextBorderStyleRoundedRect];
[textTitle setFrame:postion];
[textTitle setText:#""];
[whiteView addSubview:textTitle];
}
- (IBAction)buttonQuantityAdd:(id)sender {
[self updateRecordwithTitle:textTitle.text];
}
#end
This is what I am trying to achieve:
This is what I get using the UITextView and the code above...
I have a UITextField and UITextView in the same view but I'm having trouble with them being editable, especially when going from one to the other.
If I tap in the UITextField, I'm able to type in it. But if I then type into the UITextView, then it doesn't capture what I'm typing. And the same happens visa-versa.
Any ideas why it is behaving like this?
review = [[UITextView alloc] initWithFrame:CGRectMake(x+10, y + 40, 470-5, h - 15)];
review.keyboardType = UIKeyboardTypeAlphabet;
review.delegate = self;
review.font = [UIFont systemFontOfSize:16];
[scrollView addSubview:review];
and
titleField = [[UITextField alloc] initWithFrame:CGRectMake(x+10, y + 30, 472, 32)];
titleField.keyboardType = UIKeyboardTypeAlphabet;
titleField.clearButtonMode = UITextFieldViewModeWhileEditing;
titleField.delegate = self;
titleField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
titleField.font = [UIFont systemFontOfSize:14];
[scrollView addSubview:titleField];
Both of these are global variables and their sizes are large enough.
So I figured it out, but I'm not sure why it is this way.
The objects were being released such that my pointers weren't accurate anymore?
My .h stayed the same:
{
UITextField *titleField;
UITextView *review;
}
#property (nonatomic, retain) UITextField *titleField;
#property (nonatomic, retain) UITextView *review;
And I changed both to be like this:
UITextField *titleField1 = [[UITextField alloc] initWithFrame:CGRectMake(x+10, y + 30, 472, 32)];
titleField1.keyboardType = UIKeyboardTypeAlphabet;
titleField1.clearButtonMode = UITextFieldViewModeWhileEditing;
titleField1.delegate = self;
titleField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
titleField1.font = [UIFont systemFontOfSize:14];
[scrollView addSubview:titleField1];
titleField = [titleField1 retain];
But doesn't this leave the object hanging even after I release titleField?
You should not use both
{
UITextField *titleField;
UITextView *review;
}
#property (nonatomic, retain) UITextField *titleField;
#property (nonatomic, retain) UITextView *review;
USE:
#property (nonatomic, retain) IBOutlet UITextField *titleField;
#property (nonatomic, retain) IBOutlet UITextView *review;
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];