Can't get UITextField to autoshrink the font

2019-06-14 05:43发布

问题:

In Swift, 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 talking about a UITextField, not a UILabel or a UITextView. The reason I say this is because I have seen this question pop up several times and the answers were all based on UILabel instead of UITextField.

I hoped, that can be done in IB, where i did this settinngs of Min Font Size and ajust to fit, but this didn´t change anything:

Is there another way to resolve this?

回答1:

extension UITextField {
  internal func resizeText() {
    if let text = self.text{
      self.font = UIFont.systemFontOfSize(14)
      let textString = text as NSString
      var widthOfText = textString.sizeWithAttributes([NSFontAttributeName : self.font!]).width
      var widthOfFrame = self.frame.size.width
      // decrease font size until it fits
      while widthOfFrame - 5 < widthOfText {
        let fontSize = self.font!.pointSize
        self.font = self.font?.fontWithSize(fontSize - 0.5)
        widthOfText = textString.sizeWithAttributes([NSFontAttributeName : self.font!]).width
        widthOfFrame = self.frame.size.width
      }
    }
  }
}

Based on the answer I linked, I created an extension to UITextField that automatically resizes text - to have it properly resize the text each time, it needs to be called in a number of locations:

  • override func drawRect(rect: CGRect) (I haven't found a better spot to call this as you have to wait until its bounds are set and the TVC lifecycle gets confusing)

  • textField(textField: UITextField, shouldChangeCharactersInRange...