将UITextField增加到某个长度

编程入门 行业动态 更新时间:2024-10-25 12:17:15
本文介绍了将UITextField增加到某个长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个UITextField,我想自动调整其边界大小,以便为字段中添加的字符串空间。但是,我想在一定量的宽度上达到最大。

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?

感谢您的帮助。

EDIT:

TestingView.h

TestingView.h

#import <UIKit/UIKit.h> @interface TestingView : UIView <UITextFieldDelegate> { } @end

< .m

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

推荐答案

在委托方法 textField:shouldChangeCharactersInRange:replacementString:你应该使用 UITextField developer.apple/iphone/library/documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/occ/instm/NSString/sizeWithFont:constrainedToSize:rel =nofollow noreferrer> sizeWithFont:constrainedToSize:,并使用返回的 CGSize 的width参数设置您的 UITextField

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

更多推荐

将UITextField增加到某个长度

本文发布于:2023-10-28 08:25:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:长度   增加到   UITextField

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!