开发者

Increase UITextField to Certain Length

I have a UITextField that I would like to "automatically" adjust its bounds size in order to make space for the string added in the field. However, I would like it to max-out in terms of width at a certain amount. What is the best way that I can go about doing this?

Thanks for any help.

EDIT:

TestingView.h

#import <UIKit/UIKit.h>


@interface TestingView : UIView <UITextFieldDelegate> {

}

@end

TestingView.m

#im开发者_高级运维port "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


In the delegate method textField:shouldChangeCharactersInRange:replacementString: you should measure your UITextField's text size by using sizeWithFont:constrainedToSize: and use the returning CGSize's width parameter to set your UITextField's bounds width.

- (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);
}


Why can't you just say:

if (yourTextField.frame.size.width > self.frame.size.width) {

      yourtextField.frame.size.width = yourtextField.frame.size.width;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜