如何根据键入的文本增加文本字段的宽度?

How to increase width of textfield according to typed text?(如何根据键入的文本增加文本字段的宽度?)
本文介绍了如何根据键入的文本增加文本字段的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据其内容增加文本字段的宽度.当用户输入文本时,文本字段的大小应该会自动增加.我在此文本字段旁边有一个关闭 (X) 按钮.

I need to increase a text field's width according to its content. When the user inputs text, then the textfield size should increase automatically. I have one close (X) button next to this text field.

我限制了文本字段和按钮,使文本字段在屏幕上居中,并且按钮与它相邻.(文本字段应该是可编辑的,按钮应该是可点击的)

I have constrained the text field and button so that the text field is centered on screen, and the button is adjacent to it. (Text field should be editable, button should be clickable)

文本字段大小是这样的:

Text field size is this:

当我在其中输入文字时,大小应该会自动增加:

When I enter text in it, the size should automatically increase:

我怎样才能做到这一点?

How can I achieve this?

推荐答案

我解决了我的问题:将这个用于文本字段,不要超出屏幕.

I solve my problem : use this for textfield not go outside of screen.

 func getWidth(text: String) -> CGFloat
{
    let txtField = UITextField(frame: .zero)
    txtField.text = text
    txtField.sizeToFit()
    return txtField.frame.size.width
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    let width = getWidth(textField.text!)
    if UIScreen.mainScreen().bounds.width - 55 > width
    {
        txtWidthOfName.constant = 0.0
        if width > txtWidthOfName.constant
        {
            txtWidthOfName.constant = width
        }
        self.view.layoutIfNeeded()
    }
    return true
}

Objective C 版本

Objective C Version

-(CGFloat)getWidth:(NSString *)text{
    UITextField * textField = [[UITextField alloc]initWithFrame:CGRectZero];
    textField.text = text;
    [textField sizeToFit];
    return textField.frame.size.width;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.textFieldName.isEditing == YES) {
        CGFloat width = [self getWidth:textField.text];
        if ([UIScreen mainScreen].bounds.size.width - 60 > width) {
            self.txtWidthOfName.constant = 0.0;
            if (width > self.txtWidthOfName.constant) {
                self.txtWidthOfName.constant = width;
            }
            [self.view layoutIfNeeded];
        }
    }
    return YES;
}

这篇关于如何根据键入的文本增加文本字段的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)