Can't get UITextField to autoshrink text

后端 未结 11 822
逝去的感伤
逝去的感伤 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:53

    Swift 3.0 way to resize the font to fit:

    let startFontSize = 14.0
    let minFontSize = 7.0
    
    func resizeFont() {
        guard let font = self.font, let text = self.text else {
            return
        }
    
        let textBounds = self.textRect(forBounds: self.bounds)
        let maxWidth = textBounds.size.width
    
        for fontSize in stride(from: startFontSize, through: minFontSize, by: -0.5) {
            let size = (text as NSString).size(attributes: [NSFontAttributeName: font.withSize(CGFloat(fontSize))])
            self.font = font.withSize(CGFloat(fontSize))
            if size.width <= maxWidth {
                break
            }
        }
    }
    

提交回复
热议问题