How to increase width of textfield according to typed text?

前端 未结 8 1838
失恋的感觉
失恋的感觉 2020-12-09 04:22

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) but

相关标签:
8条回答
  • 2020-12-09 04:58

    I think this is a better solution than having a width constraint that you have to modify:

    Resize a UITextField while typing (by using Autolayout)

    - (IBAction) textFieldDidChange: (UITextField*) textField
    {
        [UIView animateWithDuration:0.1 animations:^{
            [textField invalidateIntrinsicContentSize];
        }];
    }
    

    You can omit the animation if desired..

    EDIT: Here's an example project: https://github.com/TomSwift/growingTextField

    0 讨论(0)
  • 2020-12-09 05:00

    A cheeky workaround to get width for a particular string would be

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

    And to get the width,

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

    If you have a constraint linked to txtField's width then do

    yourTxtFieldWidthConstraint.constant = width
    self.view.layoutIfNeeded() // if you use Auto layout
    

    Edit We are creating a UITextField with a frame of basically all zeros. When you call sizeToFit(), it will set the frame of UITextField in a way that it will show all of its content with literally no extra spaces around it. We only wanted its width, so I returned the width of the newly created UITextField. ARC will take care of removing it from memory for us.

    Update

    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
        }
    
    0 讨论(0)
提交回复
热议问题