How to increase width of textfield according to typed text?

前端 未结 8 1836
失恋的感觉
失恋的感觉 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:46

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

提交回复
热议问题