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

Mit*_*dav 20 uitextfield ios autolayout swift

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

我已经约束了文本字段和按钮,以便文本字段在屏幕上居中,并且按钮与它相邻.(文本字段应该是可编辑的,按钮应该是可点击的)

文本字段大小是这样的:

在此输入图像描述

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

在此输入图像描述

我怎样才能做到这一点?

Mit*_*dav 11

我解决了我的问题:用于文本字段而不是屏幕之外.

 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
}
Run Code Online (Sandbox Code Playgroud)

目标C版

-(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;
}
Run Code Online (Sandbox Code Playgroud)


Vit*_*nko 11

您可以通过覆盖UITextField类来实现它并返回自定义值 intrinsicContentSize.此外,您还需要订阅文本更改事件,并在文本更改动画时使内在内容大小无效

这是Swift 3中的示例

class Test: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupTextChangeNotification()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupTextChangeNotification()
    }

    func setupTextChangeNotification() {
        NotificationCenter.default.addObserver(
            forName: Notification.Name.UITextFieldTextDidChange,
            object: self,
            queue: nil) { (notification) in
                UIView.animate(withDuration: 0.05, animations: {
                    self.invalidateIntrinsicContentSize()
                })
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override var intrinsicContentSize: CGSize {
        if isEditing {
            if let text = text,
                !text.isEmpty {
                // Convert to NSString to use size(attributes:)
                let string = text as NSString
                // Calculate size for current text
                var size = string.size(attributes: typingAttributes)
                // Add margin to calculated size
                size.width += 10
                return size
            } else {
                // You can return some custom size in case of empty string
                return super.intrinsicContentSize
            }
        } else {
            return super.intrinsicContentSize
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 7

获得特定字符串宽度的厚颜无耻的解决方法是

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

并获得宽度,

let width = getWidth(text: "Hello world")
txtField.frame.size.width = width
self.view.layoutIfNeeded() // if you use Auto layout
Run Code Online (Sandbox Code Playgroud)

如果你有一个与txtField的宽度相关联的约束,那么就做

yourTxtFieldWidthConstraint.constant = width
self.view.layoutIfNeeded() // if you use Auto layout
Run Code Online (Sandbox Code Playgroud)

编辑 我们正在创建一个UITextField,其框架基本上都是零.当你调用sizeToFit()时,它将以一种方式设置UITextField的框架,它将显示其所有内容,并且周围没有额外的空格.我们只想要它的宽度,所以我返回了新创建的UITextField的宽度.ARC将负责将它从内存中删除.

更新

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if textField.text != nil {
            let text = textField.text! as NSString
            let finalString = text.replacingCharacters(in: range, with: string)
            textField.frame.size.width = getWidth(text: finalString)
        }

        return true
    }
Run Code Online (Sandbox Code Playgroud)


jpu*_*til 5

我们可以通过像这样设置 UITextField 约束来轻松实现:

在此处输入图片说明

//在 Xcode 9.1、Swift 4 上测试

输出:

在此处输入图片说明