i have this code for textFieldShouldEndEditing:
-(void)textFieldDidEndEditing:(UITextField *)textField
{
NSDecimalNumber *testIfNumber = [[NSDecimalNumber alloc] initWithString:[textField text]];
if (![testIfNumber isEqualToNumber:[NSDecimalNumber notANumber]])
{
NSLog(#"%#",[testIfNumber stringValue]);
[[self labelTotal]setText:[self getTotalforRate:[expenseCategorySelected categoryRate] forAmmountField:textField]];
}
}
Now my problem is that in my ViewController I have two or more textField and when a user goes directly from one to another textField this method is not fired.
Is there a method or a way to know when I'm going from a textField to another?
Thx.
You are wrong... textFieldShouldEndEditing is not for this purpose.
Just using textFieldDidEndEditing
Do like this if u dont get
#import "ViewController.h"
#interface ViewController ()<UITextFieldDelegate>//heare set the delegate
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextField *textField1 = [[UITextField alloc]initWithFrame:CGRectMake(30, 40, 200, 35)];
UITextField *textField2 = [[UITextField alloc]initWithFrame:CGRectMake(30, 80, 200, 35)];
UITextField *textField3 = [[UITextField alloc]initWithFrame:CGRectMake(30, 125, 200, 35)];
textField1.placeholder = #"I am 1st field";
textField2.placeholder = #"I am 2nd field";
textField3.placeholder = #"I am 3rd field";
//set the delegate for all text fields
textField1.delegate = self;
textField2.delegate = self;
textField3.delegate = self;
textField1.tag = 100;
textField2.tag = 200;
textField3.tag = 300;
[self.view addSubview:textField1];
[self.view addSubview:textField2];
[self.view addSubview:textField3];
}
//implement the delegate methods
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField.tag == 100)
{
NSLog(#"i am end editing -> %#",textField.text);
}
else if (textField.tag == 200)
{
NSLog(#"i am end editing -> %#",textField.text);
}
else if (textField.tag == 300)
{
NSLog(#"i am end editing -> %#",textField.text);
}
}
Hope this helps u .. :)
Related
custom UITextField: In the click TextField input,After the keyborad popup,enter the background to get enter foreground again,The app crash!
if you don't click TextField input,background or foreground conversion ,It is normal;Part of the code:
#implementatio BKSearchViewController
- (void)setNavgationView {
BKSearchBar *searchBar = [[BKSearchBar alloc] initWithFrame:CGRectMake(20, 27, kScreenWidth - 90, 30)];
searchBar.placeholder = #"输入昵称/拜托号";
searchBar.delegate = self;
[searchBar setKeyboardType:UIKeyboardTypeDefault];
[searchBar setReturnKeyType:UIReturnKeySearch];
[searchBar setPlaceholderColor:kcallColor(#"a4a4a4")];
[searchBar setPlaceholderFont:kFont(14)];
[searchBar addTarget:self action:#selector(SearchTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[navgationView addSubview:searchBar];
}
#end
//BKSearchBar The key code
#implementation BKSearchBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 设置背景
self.backgroundColor = kcallColor(#"7d1d57");
self.returnKeyType = UIReturnKeySearch;
// 设置内容 -- 垂直居中
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self UI];
}
return self;
}
- (void)UI{
// 设置左边显示一个放大镜
UIImageView *leftView = [[UIImageView alloc] init];
omit...
//右边的view
UIImageView *rightView = [[UIImageView alloc] init];
omit...
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds{
CGRect rect = CGRectMake(self.leftView.right, (self.height - 24) / 2, bounds.size.width, 14);
return rect;
}
- (void)clearText{
self.text = nil;
}
- (void)setPlaceholderColor:(UIColor *)color{
[self setValue:color forKeyPath:#"_placeholderLabel.textColor"];
}
- (void)setPlaceholderFont:(UIFont *)font{
[self setValue:font forKeyPath:#"_placeholderLabel.font"];
}
Thank all!The problem is resolved!because of the runtime!
+ (void)swizzleInstanceMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
Method otherMehtod = class_getInstanceMethod(class, otherSelector);
Method originMehtod = class_getInstanceMethod(class, originSelector);
// 交换2个方法的实现
method_exchangeImplementations(otherMehtod, originMehtod);
}
In my app I want to programmatically add textfield below another if required on click of a button. I already had provided two textFields. if a user want to add another textfield he can do so by clicking a button. I have already written code to obtain the textfield but the problem is that it overlaps the already designed textFields. How can I do it?
Is there any way through which I can get the x and Y co-ordinates of already designed textfield so that I can place new textField relative to those co-ordinates.
This code add textField to view dynamically when every click action on button
ExampleViewController.h
#import <UIKit/UIKit.h>
#interface ExampleViewController :UIViewController<UITextFieldDelegate>
#property int positionY;
#property int fieldCount;
#property (strong,nonatomic) UIScrollView *scroll;
#end
ExampleViewController.m
#import "ExampleViewController.h"
#interface ExampleViewController ()
#end
#implementation ExampleViewController
#synthesize positionY;
#synthesize fieldCount;
#synthesize scroll;
- (void)viewDidLoad {
[super viewDidLoad];
scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.backgroundColor = [UIColor whiteColor];
[self.view addSubview:scroll];
UIButton *clickToCreateTextField = [[UIButton alloc] initWithFrame:CGRectMake(40, 80, self.view.frame.size.width-80, 75)];
[clickToCreateTextField setTitle:#"Create Text Field" forState:UIControlStateNormal];
[clickToCreateTextField addTarget:self action:#selector(clickedButton) forControlEvents:UIControlEventTouchUpInside];
[clickToCreateTextField setBackgroundColor:[UIColor blackColor]];
[scroll addSubview:clickToCreateTextField];
positionY = clickToCreateTextField.center.y;
fieldCount = 0;
// Do any additional setup after loading the view.
}
-(void) clickedButton{
//add text field programmitacally
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(40, positionY, self.view.frame.size.width-80, 75)];
textField.delegate = self;
//give a tag to determine the which textField tapped
textField.tag = fieldCount;
textField.placeholder = [NSString stringWithFormat:#"Your dynamically created textField: %d", fieldCount ];
[scroll addSubview:textField];
//check if the textFields bigger than view size set scroll size and offset
if (positionY>= self.view.frame.size.height) {
scroll.contentOffset = CGPointMake(0, positionY);
scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height+positionY);
}
fieldCount++;
//increase the position with a blank place
positionY = positionY+textField.frame.size.height+20;
}
#pragma mark TextField Delegate Methods
-(void) textFieldDidBeginEditing:(UITextField *)textField{
//Do what ever you want
}
-(void) textFieldDidEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
//do anything
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
You can do any additional changes on this code.
I think this example explain your answer.
Hope it helps.
Use a counter and calculate y like this counter*texfield.frame.size.height.
I'm trying to create a class that makes a read only text field that allows the user to copy its contents. Here is my code:
CopyOnly.h
#import <UIKit/UIKit.h>
#interface CopyOnly : UITextField
#end
CopyOnly.m
#import "CopyOnly.h"
#implementation CopyOnly
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self attachTapHandler];
}
return self;
}
- (void) attachTapHandler
{
[self setUserInteractionEnabled:YES];
UIGestureRecognizer *touchy = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
[self addGestureRecognizer:touchy];
}
- (BOOL) canPerformAction: (SEL) action withSender: (id) sender
{
return (action == #selector(copy:));
}
- (void) handleTap: (UIGestureRecognizer*) recognizer
{
[self becomeFirstResponder];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setTargetRect:self.frame inView:self.superview];
[menu setMenuVisible:YES animated:YES];
}
- (void)copy:(id)sender
{
UIPasteboard *board = [UIPasteboard generalPasteboard];
[board setString:self.text];
self.highlighted = NO;
[self resignFirstResponder];
}
- (BOOL) canBecomeFirstResponder
{
return YES;
}
#end
This works great, only the keyboard is coming up. I don't want any keyboard to come up.
I tried adding this to initWithFrame:
UIView* noKeyboard = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
self.inputView = noKeyboard;
This does not give me the result I'm expecting. Anyone know how I can do this?
Extending on my comment. This is easily accomplished using a UITextView (not UITextField) with editable property set to NO.
UITextView* tf = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 50)];
tf.editable = NO;
tf.text = #"Hey this is a test!";
[self.view addSubview:tf];
Adding this to -(BOOL)canBecomeFirtResponder seemed to do the trick. Hacky, but it works.
- (BOOL) canBecomeFirstResponder
{
UIView* noKeyboard = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
self.inputView = noKeyboard;
return YES;
}
If you stuck with text field that doesn't allow editing try totally different approach. Follow instructions in this article http://nshipster.com/uimenucontroller/ to implement UILabel that supports copying.
This question already has answers here:
iOS - Dismiss keyboard when touching outside of UITextField
(38 answers)
Closed 8 years ago.
I have one TableViewCell that has UITextField in it.
I want when click out of UITextField hidden keyboard but I don't about that.
this is my code:
#implementation TextFieldCell
#synthesize Textfield,placeholder;
- (void)awakeFromNib
{
// Initialization code
Textfield = [self makeTextField];
[self addSubview:Textfield];
placeholder = [self PlaceHolderLabel];
[self addSubview:placeholder];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (UITextField *)makeTextField
{
CGRect TextFrame = CGRectMake(0,0,300,80);
UITextField *textfield = [[UITextField alloc]initWithFrame:TextFrame];
textfield.delegate = self;
textfield.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
textfield.backgroundColor = [UIColor yellowColor];
textfield.placeholder = [NSString stringWithFormat:#"Mamal"];
UIView *spacerleftView = [[UIView alloc] initWithFrame:CGRectMake(0,0,20,20)];
UIView *spacerrightView = [[UIView alloc] initWithFrame:CGRectMake(0,0,20,20)];
[textfield setLeftViewMode:UITextFieldViewModeAlways];
[textfield setRightViewMode:UITextFieldViewModeAlways];
textfield.leftView = spacerleftView;
textfield.rightView = spacerrightView;
return textfield;
}
- (UILabel *)PlaceHolderLabel{
NSString *labelText = Textfield.placeholder;
Textfield.placeholder = nil;
CGRect labelFrame = CGRectMake(0,0,280,80);
UILabel *placeholderLabel = [[UILabel alloc] initWithFrame:labelFrame];
[placeholderLabel setTextColor:[UIColor lightGrayColor]];
[placeholderLabel setText:labelText];
placeholderLabel.textAlignment = NSTextAlignmentRight;
return placeholderLabel;
}
- (UILabel *)clearPlaceHolderLabel{
NSString *labelText = nil;
CGRect labelFrame = CGRectMake(0,0,280,80);
UILabel *placeholderLabel = [[UILabel alloc] initWithFrame:labelFrame];
[placeholderLabel setText:labelText];
return placeholderLabel;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
//Keyboard becomes visible
//perform actions.
NSLog(#"start");
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
NSLog(#"end");
}
Add gesture recogniser in viewDidLoad :
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(closeKeyboard:)];
[self.view addGestureRecognizer:tap];
and then implement closeKeyboard:
- (IBAction)closeKeyboard:(id)sender {
[self.view endEditing:YES];}
my friend I had this problem but I can solve that.
you don't need add UITextField in TableViewCell , you can create TextField in ViewController or TableViewController that your tableView is inner it and then add TextField inside any cell that you want.
like this code:
ViewController.h
#interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
#property (nonatomic,strong) UITableView *table;
#property (weak,nonatomic) UITextField *Textfield;
ViewController.m
#implementation ViewController
#synthesize table,Textfield;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//add table in view
table = [self makeTableView];
[self.view addSubview:table];
[self.view setBackgroundColor: RGB(193,60,46)]; //will give a UIColor objct
//run textfield programmatically
Textfield = [self makeTextField];
//hide keyboard with hideKeyboard selector
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideKeyboard)];
[self.table addGestureRecognizer:gestureRecognizer];
}
- (void) hideKeyboard {
[Textfield resignFirstResponder];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
Try to use
[self.view setEditing:YES];
in -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
try this:
// somewhere in viewDidLoad
UITapGestureRecognizer * tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapOnBackground)];
[self.view addGestureRecognizer:tapRecognizer];
self.view.userInteractionEnabled = YES;
// ...
- (void)tapOnBackground
{
[self.view endEditing:YES];
}
Add this code in your textField implementation method.
//Set to Remove Keyboard from view
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
After that create dismissKeyboard method.
//First Responder Remove Keyboard
-(void)dismissKeyboard {
[Textfield resignFirstResponder];
}
is strange to se no question about this problem in all stack overflow, but i can't find it :(
So let me explain. I have a simple UITextField that should present a custom inputAccessoryView.
The expected behavior is:
tap in the textfield (ACTextField)
show keyboard with a textfield and a button (with cancel title)
type in some text (it have to appear in the UITextField named
inputField )
press enter and see the text appearing in the main textfield
in case i press cancel the keyboard should disappear and let the main textfield unchenged
pretty much like the Message App from Apple
And all works well exept 2 things:
if i spam key tapping on the keyboard (just to enter random text ;)
) the app freeze and Xcode show me CPU at 99% (no recovery possible)
sometimes the memory occupation grow from 2/3 MB to 40 MB just after
pressing enter and the app freeze again
Let's show some code
the .h
#import <UIKit/UIKit.h>
#interface ACTextField : UITextField
#end
the .m
#import "ACTextField.h"
#interface ACTextField () <UITextFieldDelegate>
#property (nonatomic, retain) UITextField *inputField;
#property (nonatomic, assign) BOOL keyboardOpen; // to check if keyboard is open
#property (nonatomic, retain) NSTimer *timer; //added after an answer
#end
#implementation ACTextField
// method called when timer fire
- (void) fireTimer:(NSTimer *) timer
{
[self.timer invalidate];
self.timer = nil; // this line thoesen't change anyting so can be deleted
[self.inputField becomeFirstResponder];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self awakeFromNib];
}
return self;
}
-(void)awakeFromNib
{
self.delegate = self;
self.keyboardOpen = NO;
}
- (void)cancelPressed:(id)sender
{
[self.inputField resignFirstResponder];
[self resignFirstResponder];
self.keyboardOpen = NO;
}
- (void)dealloc
{
NSLog(#"dealloc ACTextField %#", self);
self.inputField = nil;
self.timer = nil;
}
- (void) designAccessoryView
{
if (self.inputAccessoryView == nil) {
CGRect frame = [[UIScreen mainScreen] bounds];
self.inputAccessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 44)];
self.inputAccessoryView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
int buttonWidth = 65;
int padding = 5;
UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
cancel.frame = CGRectMake(padding, 0, buttonWidth, 44);
[cancel setTitle:#"cancel" forState:UIControlStateNormal];
[cancel setTitle:#"cancel" forState:UIControlStateHighlighted];
[cancel addTarget:self action:#selector(cancelPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.inputAccessoryView addSubview:cancel];
self.inputField = [[UITextField alloc] initWithFrame:CGRectMake(buttonWidth + 2*padding, 2, frame.size.width - buttonWidth - 3*padding, 40)];
self.inputField.borderStyle = UITextBorderStyleRoundedRect;
self.inputField.delegate = self;
[self.inputAccessoryView addSubview:self.inputField];
self.inputAccessoryView.backgroundColor = [UIColor lightGrayColor];
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if (!self.keyboardOpen && textField == self)
{
self.inputField.text = self.text;
[self designAccessoryView];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self // modified to use the instance method fireTimer
selector:#selector(fireTimer:)
userInfo:nil
repeats:NO];
self.keyboardOpen = YES;
}
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
self.text = self.inputField.text;
[self cancelPressed:self];
return YES;
}
#end
Any help will be greatly appreciated
EDIT: I forgot to specify that i'm testing this on my iPhone 4s with IOS 7.0.4
EDIT2: I tried using an UITextField Wrapper with pretty much the same code and all goes well. The behavior is the expected and the keyboard don't freeze anymore and the memory remain low as should be. Ok, but i need a UITextField subclass, not a wrapper :(