无法获取UITextField自动收缩字体 [英] Can't get UITextField to autoshrink the font
问题描述
在Swift中,我在表视图单元格上有一个 UITextField ,当文本太长时,我希望减小字体大小.我要说的很清楚,我在谈论的是UITextField,而不是UILabel或UITextView.我之所以这样说,是因为我已经多次看到这个问题,并且答案都基于UILabel而不是UITextField.
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.
我希望可以在IB中做到这一点,在这里我进行了最小字体大小的设置并正好适合,但这并没有改变任何东西:
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:
还有其他解决方法吗?
推荐答案
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
}
}
}
}
根据我链接的答案,我创建了UITextField
的扩展名,该扩展名会自动调整文本的大小-为使其每次都能正确调整文本的大小,需要在多个位置调用它:
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)
(我没有找到更好的地方来调用它,因为您必须等待其界限被设置并且TVC生命周期变得混乱为止)
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...
这篇关于无法获取UITextField自动收缩字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!