Append text with UITextField text - objective-c

I am running Objective-C/Cocoa in Shell in Windows, not on Mac OS X.
I want to append a string with an existing string in a text field when I click a button. I've created a button in a window, but I don't know how to append a string when I click that button.
How can I append a string to a text field when that button is clicked?

This is a pretty empty question and will probably get deleted quickly. However, to attempt to answer it in some way:
If you want to display something when you click a button then you'll need a UIButton (already added you have said) and let's say a UILabel. You can find a UILabel in the same window you discovered the button. Add it to the view, somewhere just below the button.
You then want to find the .h file that corresponds to the .xib file (if you set something up by default in XCode it will have been created for you). Let's call it MyViewController.h although it will have a different name in your app.
In that .h file, you want to create an IBAction (so that you can detect the button click in code) and an IBOutlet (so you can update the text on the label).
The code should end up looking something like this:
//
// MyViewController.h
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController {
UILabel *label;
}
#property (nonatomic, retain) IBOutlet UILabel *label;
- (IBAction)buttonClick;
#end
Then, go back to the .xib file where you created your button. Select "File's Owner", open up the "Identity inspector" under the "Tools" menu and make sure the class is set to the same name as the class whose .h file we were just editing.
Now we need to connect the button and the label. Click on the button and bring up the "connections inspector" from the "Tools" menu again. Click in the circle next to "touch up inside" and drag it to the "File's owner". Select the "buttonClick" method that pops up in a window for you. Now select the File's owner. Click in the circle next to the word "label" and drag it to the label on your iPhone screen. This has now connected up the label and the button to the code you wrote before.
Finally, save the .xib file and open up the MyViewController.m file (or whatever it is called in your app). Add the following to it:
//
// MyViewController.m
#import "MyViewController.h" // Swap this name for the name of your .h file
#implementation MyViewController
#synthesize label;
-(IBAction)buttonClick {
label.text = #"Hello World!"
}
- (void)dealloc {
[label release];
[super dealloc];
}
#end
Spend some time looking at various tutorials etc and you'll quickly get up to speed.

You didn't specify whether you're using UILabel (Cocoa Touch) or NSTextField (Cocoa). For the latter, get the field's stringValue, send that object a stringByAppendingString: message with the string you want to append, and pass the result to the field's setStringValue: method.

Short answer: create an IBAction method in a controller class and set the IBAction as the target of your button.
Long answer: Get a book and learn the details of Cocoa. Cocoa is difficult to get started with, but once you've made the initial investment you'll be able to quickly create apps. I'd recommend Cocoa Programming for Mac OS X by Aaron Hillegass. It's desktop orientated rather than iPhone, but that shouldn't put you off.
There are also loads of great web resource to learn Cocoa. Cocoa Dev Central and the Apple developer site are great places to start.

import <UIKit/UiKit.h>
#interface MyViewController : UIViewController {
    UIButton *btnToAppend;
UITextField *textfield;
}
- (IBAction)buttonClick:(id)sender;
#end
import "MyViewController.h"
#implementation MyViewController
-(void)init{
btnToAppend = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btbToAppend.frame = CGRectMake(10, 10, 100, 30);
[btnToAppend setText:#"Append Text" forState:UIControlStateNormal];
[btnToAppend addTarget:self action:#select(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubView:btnToAppend];
textfield = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 50)];
textfield.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubView:textfield];
}
-(IBAction)buttonClick:(id)sender {
NSString *string = [textfield.text stringByAppendingString:#"Welcome "];
    textfield.text = string;
}
- (void)dealloc {
    [super dealloc];
}
#end
Output will be like :
Welcome Welcome Welcome ...

Related

How I can get the value of my UITextField?

how I can get the value of my UITextField ? When I declare my UITextField in the Storyboard, I know but like this, I don't know.
(sorry for my English, I'm French)
Thank you in advance for your answer.
//Ajout d'un Text Field
CGRect rectTF = CGRectMake(10,70,100,20); // Définition d'un rectangle
UITextField *articleSaisi = [[UITextField alloc] initWithFrame:rectTF];
articleSaisi.borderStyle = UITextBorderStyleLine;
articleSaisi.placeholder = #"Article";
[self.view addSubview: articleSaisi];
I am not quite sure whether you want to access the value or you want to associate your UI element to your code:
Try this if you are saying that you want to access the text value.
atricleSaisi.text
Try to control drag the UI element to either your corresponding .h or .m file so that it can create IBOutlet for you if you are saying that you want to connect your UI element to your code.
Highly recommend you go check the documentation.
if you want to know when the user pressed return, as per your comment, then you should create a UITextViewDelegate for your text view and define its textFieldShouldReturn method:
Discussion
The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped.
Also, give a look at textFieldDidEndEditing, which is called whenever there is a focus change and you should define to correctly handle user input.
Old answer:
If I do not understand you incorrectly, you want to create a UITextField programmatically (i.e., not through a Storyboard).
In this case, you should put you initialisation code inside the viewDidLoad method of your view controller and make sure that you define a property for the text field instead of a local variable:
#interface MyViewController : UIViewController
....
#property (nonatomic, strong) UITextField* articleSaisi;
...
#end
- (void)viewDidLoad {
CGRect rectTF = CGRectMake(10,70,100,20); // Définition d'un rectangle
self.articleSaisi = [[UITextField alloc] initWithFrame:rectTF];
self.articleSaisi.borderStyle = UITextBorderStyleLine;
self.articleSaisi.placeholder = #"Article";
[self.view addSubview:self.articleSaisi];
}
If you do so, you can access the text field value from any other method in the view controller through its text property:
self.articleSaisi.text

Changing image in different view

I am attempting to change the character image in the game that I am creating but I am having some issues. I have a view controller where I will have all of the characters as their own buttons, and by selecting a button it should change the character image in the GameViewController
change.h
- (IBAction)charOne:(id)sender;
change.m
- (IBAction)charOne:(id)sender
{
GameViewController *changeView = [GameViewController game];
UIImageView *Romo = [GameView changeView];
[ChangeView setImage:[UIImage imageNamed:#"testOne.png"]];
NSLog(#"Test");
}
GameViewController.m
{
IBOutlet UIImageView *changeView;
}
#property (strong, nonatomic) IBOutlet UIImageView *changeView;
This code isn't working for me, I do not receive an error message but nothing is changed after the image is selected.
On the GameViewController the UIImage name that I am attempting to change the image for is named Romo.
Any help will be appreciated
try :
[Romo setImage:[UIImage imageNamed:#"testOne.png"]];
instead of :
[ChangeView setImage:[UIImage imageNamed:#"testOne.png"]];
You're calling the setImage method on a class rather than an instance of a class. Since Romo is the instance of UIImageView you want to affect (which is a reference pointer to the UIImageView on your game view controller), that should be the instance you affect.
Also, bad practice to name instances starting with a capital letter -- they turn out looking like classes.

TextField will NOT resign first responder with UIModalPresentationFormSheet view

I've created a button on one viewController that loads another view modally using the UIModalPresentationFormSheet presentation style. On this loaded view, I have two textFields, and I'm forcing the first textField to be first responder so that the keyboard will appear immediately with the new view. I've set up the textFields to have an action method that is hooked up to "Did End on Exit" event. However, whenever I hit "return" on the keyboard for either textField, the keyboard fails to go away (Here is my code):
// addCustomPage method that is called when button from original view is touched
- (IBAction) addCustomPage:(id)sender
{
NSLog(#"Adding Custom Page");
if (!self.customPageViewController)
{
self.customPageViewController =
[[CustomPageViewController alloc] initWithNibName:#"CustomPageViewController" bundle: nil];
}
customPageViewController.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentModalViewController:customPageViewController animated:YES];
// force keyboard to appear with loaded page on the first textField
[customPageViewController.firstTextField becomeFirstResponder];
}
#interface CustomPageViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *firstTextField;
#property (strong, nonatomic) IBOutlet UITextField *secondTextField;
- (IBAction)keyboardEndOnExit:(id)sender; // DID END ON EXIT EVENT
#end
//in CustomPageViewController.m
-(IBAction)keyboardEndOnExit:(id)sender
{
[sender resignFirstResponder];
}
This is a fairly straight forward problem, and I have no problem normally dismissing keyboards using this technique with basic views and textFields. I'm not sure if using a view in this presentation format, or set up makes things different. Thanks!
You have confirmed that you keyboardEndOnExit method is actually being called?
You could also take a more direct approach by calling [yourTextView resignFirstResponder] when a specific action is take by the user, such as a key pressed etc. I would still check if that method is ever being called using breakpoints or a log.
Have a look at this question. Pretty sure it is the same problem caused by UIModalPresentationFormSheet.

Objective-C: Adding UIButtons programmatically from another class

I'm having trouble connecting the dots between code and .xib files.
If I want to add a series of UIButtons programmatically to my view controller, how would I go about doing this from a separate class?
For instance, if I have MainViewController.m, which is set as the root view controller in Xcode, how can I add a UIButton to that view controller from SecondViewController.m? Is this even possible?
I would essentially like to place all of my "user interface" code in a separate class.
Thanks
To do this, create a UIButton *myButton programmatically and then call [mainViewController addSubview:myButton];. This may mean you need to store a MainViewController * property in your SecondViewController class.
Important methods and properties for a UIButton instance (essentially, just take a look at the documentation, but here's a minimal set of stuff to get you started):
+[UIButton buttonWithType:buttonType] - Make sure if you're doing anything remotely custom to use UIButtonTypeCustom here (it doesn't give you any default background images or otherwise to have to nil out)
setFrame: - Position the button relative to its container and set the size, for usability reasons the width and height should be at least 44 pixels (as mentioned here).
setTitle:forState: - UIControlStateNormal will act as the default properties for other states too, so you may only need to set the text here
setBackgroundImage:forState: - use UIControlStateNormal and UIControlStateHighlighted/UIControlStateSelected primarily, UIControlStateDisabled if you wish to show it grayed out or inaccessible at any point.
setImage:forState: - Use for an icon next to the button text (like an arrow pointing down for Save or up for Load, etc)
setEnabled:, setHidden:, setSelected: - Transition between different button states. setHighlighted: happens automatically when you tap the button.
addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside - TouchUpInside is almost always what you want for a simple button press, I'm using a method named buttonClicked: here to handle my button press.
Oh, and if you use [[UIButton alloc] initWith...] don't forget to [myButton release] once it's added to the mainViewController :)
use this
#import "MainViewController.h"
#interface SecondViewController
{
MainViewController *mainView;
}
#property(nonatomic, retain) MainViewController *mainView;
-(void)addButtons;
In your implementation
#synthesize mainView;
-(void)addButtons
{
UIButton *add = [UIButton alloc] init];
//do necessary stuff on button here
[self.mainView addSubview:add];
[add release];
}
In your MainViewcontroller.m
#import "SecondViewController.h"
-(void)viewDidLoad
{
[self superViewDidLoad];
SecondViewController *second = [SecondViewController alloc] init];
second.mainView = self;
[second addButton];
[second release];
}

How to programmatically change label in UIView created in a nib file?

I have trouble changing the text in a label programmatically.
When I run the following code, NSLog does display "Setting myLabel to = Hello World!", but the label on the screen is not changed.
UIViewOverlay *overlayWindow;
overlayWindow = [[[NSBundle mainBundle] loadNibNamed:#"UIViewOverlay" owner:self options:nil] objectAtIndex:0];
[self addSubview:overlayWindow];
[overlayWindow setMyLabel:#"Hello World!"];
My NIB file has a 300x300 window with some labels and buttons.
There is a label, which is connected to myLabel in the outlet. The UIView does display, just that the text cannot be changed programmatically.
UIViewOverlay.h
#import <UIKit/UIKit.h>
#interface UIViewOverlay : UIView {
IBOutlet UILabel *myLabel;
}
- (void)setMyLabel:(NSString *) label;
#end
UIViewOverlay.m
#import "UIViewOverlay.h"
#implementation UIViewOverlay
- (void)setMyLabel:(NSString *) label {
myLabel.text = label; // THIS LINE IS NOT WORKING! :-(
NSLog(#"Setting myLabel to = %#", label); // This line is working.
}
#end
Thanks in advance..
You are using an incorrect accessor name for your method to set the label string.
In cocoa, setFoo is the method by which an instance variable called foo is assigned. This isn't just a convention, many areas of functionality depend on it, for example the use of properties, key value coding etc.
In your code, your label is called myLabel. Your method to set the text of that label is called setMyLabel. Either this is causing your outlet to not be connected when the nib is loaded, as the runtime may be trying to use that method to assign the label to your instance variable in the first place, or all of the above has no effect and you have just not connected your outlet.
Make sure you have an object in your code for the label, like this example:
IBOutlet UILabel* aLabel;
And in interface builder (you may have already done this): Connect the aLabel (or whatever name you use) outlet to the actual label. This can be done by control clicking and dragging from the File’s Owner object, in the document window, to the label, in the view. A small, gray window will appear with at least two options, one will be the aLabel defined earlier, and the other will be the view (this is a default outlet required for viewcontrollers, it will have a dash to indicate it is already connected to something). Click on the aLabel option to select it. (I'll be honest, without my mac in front of me I copied most of this paragraph's instructions from this link.)
You have an object called aLabel that you can now treat like any other variable. If you want to change the text value, try this:
aLable.text = #"some text";
Maybe you did not make the connection. Can you try the following?
#import "UIViewOverlay.h"
#implementation UIViewOverlay
- (void)showMyLabel:(NSString *) label {
NSLog(#"My current label contents (myLabel) = %#", myLabel.text); // ** changed to myLabel.text
}
#end
If you aren't able to print the original value, then you aren't connected.
I hope that helps.