Reputation: 3321
I am trying to create a custom UITextField
with search bar behavior, when the UITextField
is focused, a button from the right will move in and the UITextField
size will them become smaller. And the text in the UITextField should move with animation as well. I tried the following code
[UIView animateWithDuration:0.3
animations:^(){
self.textField.frame = newFrame;
self.textField.rightView.frame = anotherNewFrame;
}];
My question is, the textfield change the size with animation with no problem. However, the rightView does not change size with animation, the text in the UITextField
simply JUMPS to the final position. How can I animate the shifting for the text?
Add these two lines in viewDidLoad
self.textfield.rightViewMode = UITextFieldViewModeAlways;
self.textfield.rightView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
And in UITextField delegate method textFieldDidBeginEditing
CGRect frame = self.textfield.frame;
frame.size.width = frame.size.width - 50.0;
[UIView animateWithDuration:0.3
animations:^(){
self.textfield.frame = frame;
}];
Still cannot get the effect desired, the text inside the textfield still jumps when the textfield changes its width with animation. I also tried
UIView *dummy = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 0.0)];
dummy.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
self.textfield.rightView = dummy;
no luck.
Upvotes: 1
Views: 2450
Reputation: 12717
Please use the code below, it should work..
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
[self toggleRightView:YES];
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
[self toggleRightView:NO];
return YES;
}
-(void)toggleRightView:(BOOL)show{
if(show){
self.txtField.rightViewMode=UITextFieldViewModeAlways;
UIView *view=[[UIView alloc] init];
CGRect rect=CGRectMake(0.0, 0.0, 50.0, 30.0);
//Place the rightview toward the right side of the textfield.
rect.origin.x=self.txtField.frame.size.width-rect.size.width;
view.frame=rect;
view.backgroundColor=[UIColor redColor];
self.txtField.rightView=view;
view.alpha=0.0;
[UIView animateWithDuration:.3 animations:^{
CGRect frame=self.txtField.frame;
frame.size.width=frame.size.width+100.0;
self.txtField.frame=frame;
self.txtField.rightView.alpha=1.0;
}];
}else{
[UIView animateWithDuration:.3 animations:^{
CGRect frame=self.txtField.frame;
frame.size.width=170.0;
self.txtField.frame=frame;
self.txtField.rightView.alpha=0.0;
} completion:^(BOOL finished) {
[self.txtField.rightView removeFromSuperview];
self.txtField.rightView=nil;
}];
}
}
Cheers.
Upvotes: 1