UITextField 子类混乱 adjustFontSizeToWidth

UITextField subclass messing adjustFontSizeToWidth

我在我的视图控制器中创建了一个子类文本字段视图,字体大小为 15,启用了 AdjustFontSizeToWidth 并且 最小字体大小为 10 。 我的文本字段有一个占位符文本太大,不适合视图。将字体大小调整为宽度已激活,系统正在将字体大小减小为 14。我不完全知道为什么 14,因为占位符仍然不适合(见截图) 知道为什么会这样吗?我错过了什么吗? 我将 UITextfield 子类化并覆盖以下方法(不确定是否相关,但这似乎是可能导致此错误的方法):

- (CGRect)leftViewRectForBounds:(CGRect)bounds {
CGRect leftViewRect = [super leftViewRectForBounds:bounds];
if ([self shouldShowLeftView] == YES) {
    CGFloat newHeight = self.frame.size.height * 0.5f;
    if (self.leftImage) {
        leftViewRect.size.width = newHeight;
    }
    leftViewRect.origin.x = kMargins;
    leftViewRect.origin.y =  (self.frame.size.height - leftViewRect.size.height) / 2.0f;
 }
 return leftViewRect;
}


- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rectForBounds = [super textRectForBounds:bounds];

if ([self shouldShowLeftView] == YES) {
    rectForBounds.origin.x += kMargins;
    rectForBounds.size.width -= 2.0 * kMargins;
} else {
    rectForBounds.origin.x += kMargins / 2.0;
    rectForBounds.size.width -= 2.0 * (kMargins / 2.0);
}
return rectForBounds;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
CGRect rectForBounds = [super editingRectForBounds:bounds];

if ([self shouldShowLeftView] == YES) {
    rectForBounds.origin.x += kMargins;
    rectForBounds.size.width -= 2.0 * kMargins;
} else {
    rectForBounds.origin.x +=  kMargins / 2.0;
    rectForBounds.size.width -= 2.0 * (kMargins / 2.0);
}
 return rectForBounds;
}

编辑:更新,我尝试使用 this solution 并对代码进行了一些调整,使其也适用于占位符。字体大小调整很好,但是 UI 当文本缩小时会弄乱,文本本身向左偏移,在左图像视图后面。在屏幕截图上,我们可以看到右边距太大,左侧的文本太多。

您没有遗漏任何东西 - 这是 iOS 的怪癖。 minimumFontSize 小于 14 的值似乎根据 my answer 对类似问题完全忽略。

将您的原始字体大小设置为 300,UITextField 仍将是 14 磅,而不是 10 磅。

14是奇幻数;未记录,但可能用于保持可读性。如果能再低点就好了。