gpt4 book ai didi

iphone - 将 UITextField 增加到一定长度

转载 作者:行者123 更新时间:2023-12-03 19:43:01 25 4
gpt4 key购买 nike

我有一个 UITextField,我想“自动”调整其边界大小,以便为字段中添加的字符串腾出空间。但是,我希望它的宽度达到一定程度的最大值。我可以采取的最佳方法是什么?

感谢您的帮助。

编辑:

测试 View .h

#import <UIKit/UIKit.h>


@interface TestingView : UIView <UITextFieldDelegate> {

}

@end

测试 View .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

最佳答案

在委托(delegate)方法中textField:shouldChangeCharactersInRange:replacementString:您应该使用 sizeWithFont:constrainedToSize: 测量 UITextField 的文本大小并使用返回的 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);
}

关于iphone - 将 UITextField 增加到一定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1817043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com