我正在尝试使用搜索栏行为创建自定义UITextField
,当UITextField
聚焦时,右侧的按钮会移入,UITextField
尺寸会变小。 UITextField中的文本也应该随动画一起移动。我尝试了以下代码
[UIView animateWithDuration:0.3
animations:^(){
self.textField.frame = newFrame;
self.textField.rightView.frame = anotherNewFrame;
}];
我的问题是,文本字段用动画改变大小没有问题。但是,rightView不会通过动画更改大小,UITextField
中的文本只是JUMPS到最终位置。如何为文本的移动设置动画?
在viewDidLoad
中添加这两行self.textfield.rightViewMode = UITextFieldViewModeAlways;
self.textfield.rightView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
在UITextField委托方法textFieldDidBeginEditing
中CGRect frame = self.textfield.frame;
frame.size.width = frame.size.width - 50.0;
[UIView animateWithDuration:0.3
animations:^(){
self.textfield.frame = frame;
}];
仍然无法获得所需的效果,当文本字段通过动画更改其宽度时,文本字段内的文本仍然会跳转。我也试过
UIView *dummy = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 0.0)];
dummy.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
self.textfield.rightView = dummy;
没有运气。
答案 0 :(得分:1)
请使用下面的代码,它应该有用..
-(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;
}];
}
}
干杯。