如何根据键入的文本增加文本字段的宽度? [英] How to increase width of textfield according to typed text?

查看:19
本文介绍了如何根据键入的文本增加文本字段的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据其内容增加文本字段的宽度.当用户输入文本时,文本字段的大小应该会自动增加.我在此文本字段旁边有一个关闭 (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;
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆