texto reemplazar predictivo poner palabras eliminar diccionario como autocorrector autocorrección aprendidas iphone ios objective-c uitextfield

iphone - reemplazar - No se puede obtener UITextField para cambiar automáticamente el texto



reemplazar texto iphone (11)

Tengo un UITextField en una celda de vista de tabla, y cuando el texto se vuelve demasiado largo, me gustaría que el tamaño de la fuente disminuya. Quiero dejar muy claro que estoy hablando de un UITextField , no un UILabel o un UITextView . La razón por la que digo esto es porque he visto aparecer esta pregunta varias veces y todas las respuestas se basaron en UILabel lugar de UITextField . Por ejemplo, alguien preguntó "No puedo hacer que mi UITextField automáticamente" y la respuesta fue: "Asegúrate de que numberOfLines esté establecido en 1 ". Que yo sepa, un UITextField ni siquiera tiene esa propiedad y es un control de línea única.

Yo he tratado:

  • en IB configurando la fuente al sistema 14.0, minFontSize a 7 y marcando la casilla "ajustar para encajar"
  • en el código en tableView:cellForRowAtIndexPath:

ptCell.name.font = [UIFont systemFontOfSize: 14.0]; ptCell.name.adjustsFontSizeToFitWidth = YES; ptCell.name.minimumFontSize = 7.0;

pero ninguno de estos ha funcionado. Con eso quiero decir que, en lugar de reducir el tamaño del texto, trunca la cola.

¿Alguien sabe lo que me estoy perdiendo? Presumiblemente esto debería funcionar porque he visto otras preguntas quejándose de que está haciendo eso cuando el usuario no quiere que lo haga.


Creo que desea establecer la propiedad adjustsFontSizeToFitWidth para su UITextField en YES, y especificar un minimumFontSize . Funciona para mí, pero agrego el UITextField programáticamente: ¿problema del IB?


El problema aquí es que minimumFontSize es una proporción y debería estar entre 0 y 1 :)

f.adjustsFontSizeToFitWidth = true f.minimumFontSize = 0.5

funciona perfectamente :)


Mi solución humilde para este problema fue la siguiente ... (encontrar el tamaño de fuente adecuado por mi cuenta - para ajustarlo al tamaño del marco) Lo hice dentro del método delegado de shouldChangeCharactersInRange: replacementString:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // bla bla ... anything inside method you want to do // reset font size of textfield textField.font = [FONT_PROXY fontNormalOfSizeNormal]; CGFloat widthOfText = [textField.text sizeWithAttributes:@{NSFontAttributeName:textField.font}].width; CGFloat widthOfFrame = textField.frame.size.width; // decrease font size until it fits (25 is constant that works for me) while((widthOfFrame - 25) < widthOfText){ CGFloat fontSize = textField.font.pointSize; textField.font = [textField.font fontWithSize:fontSize - 0.5f]; widthOfText = [textField.text sizeWithAttributes:@{NSFontAttributeName:textField.font}].width; widthOfFrame = textField.frame.size.width; } }


Probado con XCode8 y Swift 3.0.1

func getTextfield(view: UIView) -> [UITextField] { var results = [UITextField]() for subview in view.subviews as [UIView] { if let textField = subview as? UITextField { results += [textField] } else { results += getTextfield(view: subview) } } return results } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let allTextFields = getTextfield(view: self.view) for textField in allTextFields { textField.font = UIFont.boldSystemFont(ofSize: 14) var widthOfText: CGFloat = textField.text!.size(attributes: [NSFontAttributeName: textField.font!]).width var widthOfFrame: CGFloat = textField.frame.size.width while (widthOfFrame - 15) < widthOfText { // try here to find the value that fits your needs let fontSize: CGFloat = textField.font!.pointSize textField.font = textField.font?.withSize(CGFloat(fontSize - 0.5)) widthOfText = (textField.text?.size(attributes: [NSFontAttributeName: textField.font!]).width)! widthOfFrame = textField.frame.size.width } } }

Usé viewDidLayoutSubviews para obtener todos los campos de texto y autoenlazar el texto.

Tal vez alguien necesite este código.

Para mi funciona perfecto.

El Código es de @ Marek Manduch en este sitio y de

@ Kunal Kumar en este sitio: cómo obtener todos los campos de texto de una vista en swift


Prueba esto esta funcionando para mi (swift 3.0)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // bla bla ... anything inside method you want to do // reset font size of textfield textField.font = UIFont.systemFont(ofSize: CGFloat(15.0)) var widthOfText: CGFloat = textField.text!.size(attributes: [NSFontAttributeName: textField.font!]).width var widthOfFrame: CGFloat = textField.frame.size.width // decrease font size until it fits (25 is constant that works for me) while (widthOfFrame - 25) < widthOfText { let fontSize: CGFloat = textField.font!.pointSize textField.font = textField.font?.withSize(CGFloat(fontSize - 0.5)) widthOfText = (textField.text?.size(attributes: [NSFontAttributeName: textField.font!]).width)! widthOfFrame = textField.frame.size.width } return true }


Se puede resolver seleccionando Saltos de línea = Clip en IB


Swift 3.0 forma de cambiar el tamaño de la fuente para adaptarse:

let startFontSize = 14.0 let minFontSize = 7.0 func resizeFont() { guard let font = self.font, let text = self.text else { return } let textBounds = self.textRect(forBounds: self.bounds) let maxWidth = textBounds.size.width for fontSize in stride(from: startFontSize, through: minFontSize, by: -0.5) { let size = (text as NSString).size(attributes: [NSFontAttributeName: font.withSize(CGFloat(fontSize))]) self.font = font.withSize(CGFloat(fontSize)) if size.width <= maxWidth { break } } }


Tuve este mismo problema con los UITextFields creados en StoryBoard en Xcode 5.0.2, ejecutando iOS 7.0.4. Me di cuenta de que StoryBoard, viewDidLoad o viewWillAppear no podían cambiar la propiedad .minimumFontSize, pero sí se podía cambiar en viewDidAppear. Así que el siguiente código solucionó mi problema:

- (void) viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; self.myTextField.minimumFontSize = 4.0; [self.myTextField setNeedsLayout]; [self.myTextField layoutIfNeeded]; }


Usé la respuesta publicada por @Purva como punto de partida para encontrar este método que proporciona el tamaño de fuente requerido comenzando en el tamaño de fuente configurado, y no para caer por debajo del tamaño de fuente mínimo configurado. Mientras que @Purva probó la altura del texto, necesitaba el ancho para ajustarlo. Este método se puede colocar en una categoría o en una subclase de UITextField. Lo tengo en una subclase que también captura el UITextFieldTextDidChangeNotification . Desde este controlador de notificaciones, llamo al nuevo método y redimensiono la fuente si es necesario. También lo llamo cuando estoy asignando nuevo texto al campo de texto para asegurarme de que se ajustará a las subclases - (void)setText: (NSString*)text .

En cada caso, cuando lo llamo estoy usando el siguiente código:

CGFloat requiredFontSize = self.requiredFontSize; if( self.font.pointSize != requiredFontSize ) { self.font = [self.font fontWithSize: requiredFontSize]; }

Aquí está el nuevo método:

- (CGFloat)requiredFontSize { const CGRect textBounds = [self textRectForBounds: self.frame]; const CGFloat maxWidth = textBounds.size.width; if( _originalFontSize == -1 ) _originalFontSize = self.font.pointSize; UIFont* font = self.font; CGFloat fontSize = _originalFontSize; BOOL found = NO; do { if( font.pointSize != fontSize ) { font = [font fontWithSize: fontSize]; } CGSize size = [self.text sizeWithFont: font]; if( size.width <= maxWidth ) { found = YES; break; } fontSize -= 1.0; if( fontSize < self.minimumFontSize ) { fontSize = self.minimumFontSize; break; } } while( TRUE ); return( fontSize ); }


Yo tuve el mismo problema. El UITextField dejó de encoger el texto cuando era demasiado largo, pero en cambio se redimensionó y creció fuera de sus "límites".

La solución que me ayudó fue establecer una restricción de ancho en un UITextField dado. Después de eso, ya no creció, en cambio, el texto en su interior se hizo más pequeño como se esperaba. (Por supuesto, debe configurar minFontSize y marcar la casilla "Ajustar para encajar" en el guión gráfico).

Sé que es un poco tarde, pero si alguien más encuentra esta pregunta a través de Google como lo hice ... podría ayudar.


-(BOOL)sizeFontToFit:(NSString*)aString minSize:(float)aMinFontSize maxSize:(float)aMaxFontSize { float fudgeFactor = 16.0; float fontSize = aMaxFontSize; self.font = [self.font fontWithSize:fontSize]; CGSize tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight); CGSize stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; while (stringSize.height >= self.frame.size.height) { if (fontSize <= aMinFontSize) // it just won''t fit return NO; fontSize -= 1.0; self.font = [self.font fontWithSize:fontSize]; tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight); stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; } return YES; }