Aumenta UITextField a una certa lunghezza
-
08-07-2019 - |
Domanda
Ho un UITextField che vorrei "automaticamente" regolare le dimensioni dei limiti per creare spazio per la stringa aggiunta nel campo. Tuttavia, vorrei che massimizzasse in termini di larghezza per un determinato importo. Qual è il modo migliore che posso fare per farlo?
Grazie per l'aiuto.
Modifica
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
Soluzione
Nel metodo delegato textField: shouldChangeCharactersInRange: sostituzioneString: devi misurare le dimensioni del tuo UITextField
usando
Altri suggerimenti
Perché non puoi semplicemente dire:
if (yourTextField.frame.size.width > self.frame.size.width) {
yourtextField.frame.size.width = yourtextField.frame.size.width;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow