Can't get UITextField to autoshrink the font

一笑奈何 提交于 2019-12-23 05:18:02

问题


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...



来源:https://stackoverflow.com/questions/37399573/cant-get-uitextfield-to-autoshrink-the-font

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!