ios - UITextField 子类困惑 adjustFontSizeToWidth

标签 ios objective-c uitextfield uikit subclass

我在我的 View Controller 中创建了一个子类文本字段 View ,字体大小为 15,启用了 AdjustFontSizeToWidth 并且最小字体大小为 10。 我的文本字段有一个占位符文本太大,不适合 View 。将字体大小调整为宽度已激活,系统正在将字体大小减小到 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;
}

placeholder not fitting in the screen

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

最佳答案

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

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

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

关于ios - UITextField 子类困惑 adjustFontSizeToWidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30785785/

相关文章:

iphone - Cocoa 和 iPhone 开发之间的差异

ios - 第二次点击 UITextField(在 UITableViewCell 子类中)意外地关闭键盘

ios - 在用户点击屏幕的任何位置创建一个 UITextField

ios - 选择器到 NSString 到 UITextField

Android 无法从 redux 获取对象数组

ios - Swift:将参数值传递给选择器函数

ios - Xcode 11 Beta - Storyboard ViewControllers 显示为黑色

objective-c - 如何从 NSManagedObjectContext 中删除新对象

ios - 在文本字段内点击时如何添加 UIPickerView?

iphone - 在运行时获取 iPhone/iPad/iPod Touch 的 ppi