iOS 如何根据屏幕大小类调整 UILabel 或 UITextField 字体大小?

标签 ios autolayout uitextfield uifont size-classes

我正在使用大小类和自动布局构建界面。我遇到的问题之一是我不能再为文本字段使用固定的字体大小——在较小的屏幕上会看到更少的文本。

其中一种解决方案是使用“调整以适合”,但该选项仅在有足够的文本水平溢出文本字段时才有效。 enter image description here

当运行时的 UITextField 大小未知时,使用字体大小的正确解决方案是什么?

最佳答案

我正在为所有标签使用自定义类,并在设计时分配两个属性。一个是 autoFont,另一个是 fontSize,它是设计时 iPhone 4 英寸 xib 中当前的字体大小。这是类(class)。

.h 文件

#import <UIKit/UIKit.h>

@interface CustomLabel : UILabel

@property (nonatomic) IBInspectable BOOL autoFont;

@property (nonatomic) IBInspectable CGFloat fontSize;

@end

这是 .m 文件

#import "CustomLabel.h"

@implementation CustomLabel

@synthesize autoFont;
@synthesize fontSize;

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (autoFont) {
        float newFontSize = [UIScreen mainScreen].bounds.size.height * (fontSize / 568.0);
        if ([UIScreen mainScreen].bounds.size.height < 500) {
            newFontSize = [UIScreen mainScreen].bounds.size.height * (fontSize / 480.0);
        }
        self.font = [UIFont fontWithName:self.font.fontName size:newFontSize];
    }
}

@end

我认为这是解决此类问题的最简单方法,而且我已经使用自定义类对按钮和文本字段做了同样的事情。

关于iOS 如何根据屏幕大小类调整 UILabel 或 UITextField 字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31790979/

相关文章:

ios - 没有重复使用的表格单元格的索引路径

ios - 创建一个圆形颜色选择器

ios - 改变uitextfield的边框颜色

iPhone UITextView 可滚动但不可编辑

iOS UIWebView loadRequest 耗时太长

ios - Cocoapods 和 ruby​​_executable_hooks : no such file or directory

ios - 有没有办法通过代码创建大于或等于关系的约束

uinavigationbar - 使用 UINavigationBar 和 UIBarButtonItem 自动布局

ios - 自动布局何时可以推断宽度和水平位置?

objective-c - UITextField 设置可见?