[英]Can't get UITextField to autoshrink the font
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. 在Swift中,我在表格视图单元格上有一个UITextField ,当文本太长时,我希望减小字体大小。 I want to make it very clear that I am talking about a UITextField, not a UILabel or a UITextView. 我想说的很清楚,我在谈论的是UITextField,而不是UILabel或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. 我之所以这样说,是因为我已经多次看到此问题,并且答案都基于UILabel而不是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: 我希望可以在IB中做到这一点,在IB中我做了最小字体大小的设置,只是为了适应,但这并没有改变任何东西:
Is there another way to resolve this? 还有另一种解决方法吗?
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: 根据我链接的答案,我创建了UITextField
的扩展,该扩展会自动调整文本的大小-为使其每次都能正确调整文本的大小,需要在多个位置调用它:
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) override func drawRect(rect: CGRect)
(我还没有找到更好的方法来调用它,因为您必须等到其界限设置好并且TVC生命周期变得令人困惑时才使用)
textField(textField: UITextField, shouldChangeCharactersInRange...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.