Can't get UITextField to autoshrink text

后端 未结 11 823
逝去的感伤
逝去的感伤 2020-12-05 14:25

I have a UITextField on a table view cell, and when it\'s text becomes too long I would like the font size to decrease. I want to make it very clear that I am t

11条回答
  •  误落风尘
    2020-12-05 14:54

    Try this its working for me (swift 3.0)

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            // bla bla ... anything inside method you want to do
            // reset font size of textfield
            textField.font = UIFont.systemFont(ofSize: CGFloat(15.0))
            var widthOfText: CGFloat = textField.text!.size(attributes: [NSFontAttributeName: textField.font!]).width
            var widthOfFrame: CGFloat = textField.frame.size.width
            // decrease font size until it fits (25 is constant that works for me)
            while (widthOfFrame - 25) < widthOfText {
                let fontSize: CGFloat = textField.font!.pointSize
                textField.font = textField.font?.withSize(CGFloat(fontSize - 0.5))
                widthOfText = (textField.text?.size(attributes: [NSFontAttributeName: textField.font!]).width)!
                widthOfFrame = textField.frame.size.width
            }
            return true
        }
    

提交回复
热议问题