我有一个 UITextField,我想“自动”调整其边界大小,以便为字段中添加的字符串腾出空间。但是,我希望它的宽度达到一定程度的最大值。我可以采取的最佳方法是什么?
谢谢你的帮助。
EDIT:
测试视图.h
#import <UIKit/UIKit.h>
@interface TestingView : UIView <UITextFieldDelegate> {
}
@end
测试视图.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
在委托方法中文本字段:shouldChangeCharactersInRange:替换字符串: http://developer.apple.com/iphone/library/documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html#//apple_ref/occ/intfm/UITextFieldDelegate/textField:shouldChangeCharactersInRange:replacementString:你应该测量你的UITextField
的文本大小使用sizeWithFont:constrainedToSize: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/occ/instm/NSString/sizeWithFont:constrainedToSize:并使用返回的CGSize
的宽度参数来设置你的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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)