Aumentar UITextField a cierta longitud
-
08-07-2019 - |
Pregunta
Tengo un UITextField que me gustaría "automáticamente" ajusta el tamaño de sus límites para hacer espacio para la cadena agregada en el campo. Sin embargo, me gustaría que alcanzara el máximo en términos de ancho en cierta cantidad. ¿Cuál es la mejor manera en que puedo hacer esto?
Gracias por cualquier ayuda.
EDIT:
TestingView.h
#import <UIKit/UIKit.h>
@interface TestingView : UIView <UITextFieldDelegate> {
}
@end
TestingView.m
#import "TestingView.h"
@implementation TestingView
- (void)awakeFromNib
{
CGRect testingBounds = self.bounds;
testingBounds.size.width = testingBounds.size.width - 20;
testingBounds.size.height = 30;
CGPoint testingCenter = self.center;
testingCenter.y = testingCenter.y - 75;
UITextField *testingField = [[UITextField alloc] initWithFrame:testingBounds];
testingField.center = testingCenter;
testingField.delegate = self;
testingField.placeholder = @"Testing";
[self addSubview:testingField];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int yourMaxWidth = 150;
float width = [textField.text sizeWithFont:
[UIFont systemFontOfSize: 14]
constrainedToSize:
CGSizeMake(yourMaxWidth, textField.bounds.size.height)].width;
textField.bounds = CGRectMake(textField.bounds.origin.x,
textField.bounds.origin.y,
width,
textField.bounds.size.height);
return YES;
}
@end
Solución
En el método delegado textField: shouldChangeCharactersInRange: replaceString: debe medir el tamaño del texto de UITextField
utilizando y use el parámetro de ancho de CGSize
de retorno para establecer el ancho de los límites de UITextField
.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
float width = [yourTextField.text sizeWithFont:
[UIFont systemFontOfSize: 14]
constrainedToSize:
CGSizeMake(yourMaxWidth, yourTextField.bounds.size.height)].width;
yourTextField.bounds = CGRectMake(yourTextField.bounds.origin.x,
yourTextField.bounds.origin.y,
width,
yourTextField.bounds.size.height);
}
Otros consejos
¿Por qué no puedes simplemente decir:
if (yourTextField.frame.size.width > self.frame.size.width) {
yourtextField.frame.size.width = yourtextField.frame.size.width;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow