Create UITextField on UIView but can not get text input - ios

I am using Xcode 6 and doing a small project on iOS 8, and I need to render some text onto the View.
My method is to create a UITextField on a UIView and as long as people type onit, the app redraw the View:
- (void)viewDidLoad {
[super viewDidLoad];
self.renderTextView.textToRender = #"Please type something…";
UITextField* textField = [[UITextField alloc] initWithFrame:self.renderTextView.frame];
textField.opaque = NO;
[self.renderTextView addSubview:textField];
[textField addTarget:self action:#selector(updateLabelAndRefresh:) forControlEvents:UIControlEventEditingChanged];
}
- (void) updateLabelAndRefresh: (id)sender{
self.renderTextView.textToRender = #"Hello World";
// if text's length > 0 …
if (self.textField.text.length > 0) {
self.renderTextView.textToRender = self.textField.text;
}
[self.renderTextView setNeedsDisplay];
}
But the problem is: no matter how I try, I can not get the actual text I type on my phone. and the console showed me that the text is null. I kept googling it but I stil can not work it out.
Do you guys have any solution? Thank you ;)

In below some error is there, give a look.
- (void)viewDidLoad {
[super viewDidLoad];
//Here textField is local variable
UITextField* textField = [[UITextField alloc] initWithFrame:self.renderTextView.frame];
textField.opaque = NO;
}
- (void) updateLabelAndRefresh: (id)sender{
self.renderTextView.textToRender = #"Hello World";
// if text's length > 0 …
if (self.textField.text.length > 0) { //Then how come u getting self.textField here and using it as global one.
//So you won't get access to that locally defined textField in viewDidLoad method.
self.renderTextView.textToRender = self.textField.text;
}
}
Please check your code and update me about it.

Related

How to set custom cursor position of UITextField?

When user clicks on UITextFiled the cursor is at starting point, for design purpose its not look good. So, I want to change postion of cursor +5 or from center of UITextField.
I had implemented this code found from Github, Stil its not working. Please help me if you can guide me how to solve this problem.
My code is below
#import "UITextField+Selection.h"
#implementation UITextField (Selection)
- (NSRange)selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void)setSelectedRange:(NSRange)range
{
UITextPosition* beginning = self.beginningOfDocument;
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
#import "UITextField+Selection.h"
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.nameTextField setSelectedRange:NSMakeRange(5,0)]; // Category method called
}
#end
Instead of moving the cursor you can add padding to the left of the UITextFiled like this for design to look better
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
If you want to have custom position of cursor when user selects UITextField you need to register for notification that is posted when user selects UITextField.
So you can add yourself as observer (for example in viewDidLoad method) via:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(textFieldSelected) name:UITextFieldTextDidBeginEditingNotification object:nil];
And then in textFieldSelected method you can:
- (void)textFieldSelected {
[self.nameTextField setSelectedRange:NSMakeRange(5,0)];
}
For designing purpose, You can put Image behind UITextview, and put textview above UIImage view. It will look good for design

How do I centre UITextField cursor after user input consistently

I have a UITextField that I want to centre all content (text, cursor) at all times. Is this possible in iOS 7? My current initialisation of the view is shown below.
self.textField = [[UITextField alloc] init];
self.textField.delegate = self;
[self.textField setTextAlignment:NSTextAlignmentCenter];
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
self.textField.placeholder = NSLocalizedString(#"Enter some text", #"The placeholder text to use for this input field");
My requirement for this is that when I click in the UITextField, the placeholder text should disappear, and show the cursor in the middle of the UITextField.
Currently, this seems to be intermittently positioned either in the middle of the text field or on the left of the text field irrelevant of where I click. Anybody got any suggestions as to how I can solve this or is it a known issue in iOS?
If you're creating you UITextField in you Storyboard you should not initialise and alloc it in code.
You need to use you Textfield delegates to accomplish this..
- (void)viewDidLoad
{
[super viewDidLoad];
self.textField.delegate = self;
[self.textField setTextAlignment:NSTextAlignmentCenter];
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
[self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
self.textField.placeholder = #"Enter some text";
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
//this removes your placeholder when textField get tapped
self.textField.placeholder = nil;
//this sets your cursor to the middle
self.textField.text = #" ";
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.textField.placeholder = #"The placeholder text to use for this input field";
}
This surely does the trick.. Please accept the answer if it helps.
UPDATE
With code below when user press backspace the cursor will not align the text to the left.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:string];
NSLog(#"propose: %#", proposedNewString);
if ([proposedNewString isEqualToString:#""])
{
textField.text = [#" " stringByAppendingString:textField.text];
}
return YES;
}

Issue in deleting the textfield

I have two buttons for adding and deleting the textfields. Adding works fine but when I click on delete it deletes only the last added textfield. Here are my two methods:
-(void)addTextField {
keyTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, yAxisDistance, 150, 30)];
keyTextField.borderStyle = UITextBorderStyleRoundedRect;
keyTextField.placeholder = #"Key Value";
keyTextField.delegate = self;
[self.view addSubview:keyTextField];
valueTextField = [[UITextField alloc] initWithFrame:CGRectMake(165, yAxisDistance, 150, 30)];
valueTextField.borderStyle = UITextBorderStyleRoundedRect;
valueTextField.placeholder = #"Value";
valueTextField.delegate = self;
[self.view addSubview:valueTextField];
yAxisDistance = yAxisDistance+35;
}
-(void)deleteTextField {
[keyTextField removeFromSuperview];
[valueTextField removeFromSuperview];
yAxisDistance = yAxisDistance-35;
}
I know it's an small issue but I am very new to this field so kindly help.
Use this code for remove specific textfield from UIView. But First you have to set tag of every UITextField in view when you create or add it in view.
for ( UITextField* textField in view.subviews )
{
if(textField.tag== 1)
{
[textField removeFromSuperview];
}
}
I think the problem lies with the outlet. Can you check the following:
Open the outlets that are connected to the textifeld in the IB. There should be gray dots inside circles on the left side of the editor. Are they seem correct for both text fields?
Setup a breakpoint inside deleteTextField method and check the two textfields. Verify that both properties are not nil.
PS: You don't need to add tags to your view, using properties is perfectly fine and even better in my opinion. The reason for your problem is something else. Also, you do not need to removeFromSuperview, you can also setHidden:YES.
Sorry that time I was not understand your problem...
I done with this:
Declare one
NSMutableArray *allTextfieldArray;
and initialise in
viewdidload
method..
now do:
-(void)addTextField {
keyTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, yAxisDistance, 150, 30)];
keyTextField.borderStyle = UITextBorderStyleRoundedRect;
keyTextField.placeholder = #"Key Value";
keyTextField.delegate = self;
[self.view addSubview:keyTextField];
valueTextField = [[UITextField alloc] initWithFrame:CGRectMake(165, yAxisDistance, 150, 30)];
valueTextField.borderStyle = UITextBorderStyleRoundedRect;
valueTextField.placeholder = #"Value";
valueTextField.delegate = self;
[self.view addSubview:valueTextField];
yAxisDistance = yAxisDistance+35;
[allTextfieldArray addObject:keyTextField];
[allTextfieldArray addObject:valueTextField];
}
if ([allTextfieldArray count]>0) {
UITextField *txtField = [allTextfieldArray lastObject];
[allTextfieldArray removeLastObject];
[txtField removeFromSuperview];
txtField = nil;
UITextField *txtField2 = [allTextfieldArray lastObject];
[allTextfieldArray removeLastObject];
[txtField2 removeFromSuperview];
txtField2 = nil;
yAxisDistance = yAxisDistance-35;
}
you store the last textField in your variables keyTextField and valueTextField. So when you call your deleteTextField the last both will be deleted. you must track which textFileds you want exactly to delete.
for example you could give all your textFields a tag number when you create them:
first create an int as counter:
#implementation YourClass {
int tagcounter;
}
in init method set your counter:
tagcounter = 0;
in your addTextField:
keyTextField.tag = tagcounter++;
valueTextField.tag = tagcounter++;
when the delete button is tapped, you must know the textfield tags and pass them to your deleteTextField method. There you could do something like:
-(void)deleteTextFieldWithTag:(int)tagnumber {
for (UIView *view in [self.view subviews])
{
if ([view isKindOfClass:[UITextField class]])
{
if (view.tag == tagnumber || view.tag == tagnumber+1) {
[view removeFromSuperview];
}
}
}

iOS: Keyboard freezes on device but works in simulator

Whenever I go to enter text in a subclassed UITextfield on the device, I'll get two or three characters entered and then the app freezes. Can't dismiss the keyboard or touch any tabs. Here's the UITextField subclass:
#implementation OAI_TextField
#synthesize elementID;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
colorManager = [[OAI_ColorManager alloc] init];
fileManager = [[OAI_FileManager alloc] init];
self.font = [UIFont fontWithName:#"Helvetica" size:20.0];
self.textColor = [colorManager setColor:66.0 :66.0 :66.0];
self.borderStyle = UITextBorderStyleRoundedRect;
self.backgroundColor = [UIColor whiteColor];
self.returnKeyType = UIReturnKeyDone;
self.delegate = self;
}
return self;
}
#pragma mark Text Field Delegate Methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self resignFirstResponder];
//if project number text field we're going to check and see if the "Project" directory contains the file, if not we'll create it
//get super view
UIView* myParent = self.superview;
//get the subviews
NSArray* mySiblings = myParent.subviews;
//get the label
UILabel* myLabel = [mySiblings objectAtIndex:0];
//get the label text
NSString* myLabelText = myLabel.text;
//check it!
if ([myLabelText isEqualToString:#"Project Number:"]) {
NSString* projectNumberPlist = [NSString stringWithFormat:#"%#.plist", self.text];
NSString* projectNumberPlistPath = [NSString stringWithFormat:#"Projects/%#", projectNumberPlist];
[fileManager createFile:projectNumberPlist:projectNumberPlistPath];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(#"ok");
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
I'll get the NSLog call in - (void)textFieldDidBeginEditing:. I do not get any error messages in the console. Not really sure where to begin debugging this. Could someone give me a nudge?
Thanks

How to add multiple UITextfield in iOS 5?

How do I create and add multiple UITextField to my controller?
I can create one, like this:
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(5,5,100,25)];
tf.borderStyle = UITextBorderStyleRoundedRect;
[tf setReturnKeyType:UIReturnKeyDefault];
[tf setEnablesReturnKeyAutomatically:YES];
[tf setDelegate:self];
[self.view addSubview:tf]
But do I need to do that for each UITextField?
Whats the best approach to template UI Controls?
Put it in a loop, offset each text field's Y position and tag each text field:
for (int i = ; i < numberOfTextFieldsNeeded; i++) {
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(5, 5 + 35 * i ,100,25)]; // 10 px padding between each view
tf.tag = i + 1; // tag it for future reference (+1 because tag is 0 by default which might create problems)
tf.borderStyle = UITextBorderStyleRoundedRect;
[tf setReturnKeyType:UIReturnKeyDefault];
[tf setEnablesReturnKeyAutomatically:YES];
[tf setDelegate:self];
[self.view addSubview:tf]
// don't forget to do [tf release]; if not using ARC
}
Then in delegate methods perform actions based on tag of the textField that called each delegate method. For example to switch to next text view when user taps return key:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
UITextField *nextTextField = [self.view viewWithTag:textField.tag + 1];
[nextTextField becomeFirstResponder];
}
Keep in mind that sending messages to nil in Objective-C will not crash so it will be perfectly fine when user taps return key in last text field as UITextField *nextTextField = [self.view viewWithTag:textField.tag + 1]; will return nil, and calling becomeFirstResponder on nil will do nothing. But you can check if nextTextField is nil and do something else then, whatever you like.
You can use interface builder to create a view (bigger than the size that the screen fits) and programmatically add it to a scrollView.
This is in my opinion the best approach.

Resources