How to increase width of textfield according to typed text?

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

    We can easily make it by setting UITextField constraints like this:

    //Tested on Xcode 9.1, Swift 4

    Output:

    0 讨论(0)
  • 2020-12-09 04:40

    You can achieve it with overriding UITextField class and return custom value in intrinsicContentSize. Also you need to subscribe to text change event and invalidate intrinsic content size on text change animated

    Here is example in 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
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-09 04:40

    The answers all require a bunch of code, but you can do everything interface builder; no code needed.

    Just embed the textField in a UIStackView and constrain the stackView to be less than or equal to its superview minus some constant (if you want you can also give it a minimum width). The stackView will take care of always making the textField its intrinsic size, or the maxwidth of the stackView (which ever is smaller), so as you type the size changes automatically to fit the content.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-09 04:46

    Seems so frustrating that there is no direct way like there is "Autoshrink" to "Minimum Font size" for UILabel in IB itself. The "Adjust to Fit" in IB for a textfield is no good too.

    Why does Apple make us write all this boilerplate code, when a text field needs Autoshrink as much if not more than the UILabel!

    0 讨论(0)
  • 2020-12-09 04:57

    Implement following method of UITextFieldDelegate. Use approach provided by Matt to get required width of textField. In auto layout make sure you have centre and width constraints set for textfield. Create IBOutlet for your width constraint in code file. Also make sure you set delegate property of your textField

    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         let width = getWidth(text : textField.text)
         if width > widthConstraint.constant {
             widthConstraint.constant = width
         }
         self.layoutIfNeeded() 
         return true
    }
    
    0 讨论(0)
提交回复
热议问题