答案 0 :(得分:1)
试试这个:
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 txtFieldWidth = getWidth(textField.text!)
if UIScreen.mainScreen().bounds.width - 100 > txtFieldWidth {
txtWidthOfName.constant = 0.0
if txtFieldWidth > txtWidthOfName.constant {
txtWidthOfName.constant = txtFieldWidth
}
self.view.layoutIfNeeded()
}
return true
}