[英]UITextField change rightview size with animation
我正在尝试创建具有搜索栏行为的自定义UITextField
,当将UITextField
聚焦时,将向右移动一个按钮,并且UITextField
尺寸将变小。 UITextField中的文本也应随动画一起移动。 我尝试了以下代码
[UIView animateWithDuration:0.3
animations:^(){
self.textField.frame = newFrame;
self.textField.rightView.frame = anotherNewFrame;
}];
我的问题是,文本字段可以通过动画毫无问题地更改大小。 但是,rightView不会随动画改变大小, UITextField
的文本只是跳到最终位置。 如何为文本的移动制作动画?
在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;
没运气。
请使用下面的代码,它应该可以工作。
-(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;
}];
}
}
干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.