زيادة UITextField معينة طول
-
08-07-2019 - |
سؤال
لدي UITextField أود أن "تلقائيا" ضبط حدوده حجم لجعل مساحة السلسلة وأضاف في الميدان.ولكن أود أن ماكس-من حيث عرض على مبلغ معين.ما هي أفضل طريقة يمكن أن تذهب عن القيام بذلك ؟
شكرا على أي مساعدة.
تحرير:
TestingView.ح
#import <UIKit/UIKit.h>
@interface TestingView : UIView <UITextFieldDelegate> {
}
@end
TestingView.م
#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
المحلول
في مندوب طريقة الحقل النصي:shouldChangeCharactersInRange:replacementString: يجب قياس الخاص بك UITextField
's حجم النص باستخدام sizeWithFont:constrainedToSize: واستخدام العودة CGSize
's عرض المعلمة لتعيين UITextField
's حدود العرض.
- (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);
}
نصائح أخرى
لماذا لا يمكنك فقط أن أقول:
if (yourTextField.frame.size.width > self.frame.size.width) {
yourtextField.frame.size.width = yourtextField.frame.size.width;
}
لا تنتمي إلى StackOverflow