A tricky workaround to get the width for a particular row 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 have txtField width constraint do
yourTxtFieldWidthConstraint.constant = width self.view.layoutIfNeeded()
Edit We create a UITextField with a frame of basically all zeros. When you call sizeToFit (), it sets the UITextField frame so that it displays all its contents with literally no extra spaces around it. We just wanted its width, so I returned the width of the newly created UITextField. ARC will take care to remove 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 }
Matt Jan 03 '17 at 5:25 2017-01-03 05:25
source share