簡體   English   中英

iOS如何根據屏幕的大小類調整UILabel或UITextField字體大小?

[英]iOS how to adjust UILabel or UITextField font size based on screen's size class?

我正在使用尺寸類和自動布局構建界面。 我遇到的問題之一是我不能再為文本字段使用固定的字體大小-在較小的屏幕上將看不到更少的文本。

解決方案之一是使用“調整以適合”,但是該選項僅在有足夠的文本使文本字段水平溢出時才起作用。 在此處輸入圖片說明

當運行時UITextField大小未知時,要使用的字體大小的正確解決方案是什么?

我對所有標簽都使用了自定義類,並在設計時分配了兩個屬性。 一個是autoFont,另一個是fontSize,當前是設計時iPhone 4英寸xib中的字體大小。 這是課程。

.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

我認為這是解決此類問題的最簡單方法,我也通過使用自定義類對按鈕和文本字段進行了同樣的操作。

我知道非界面生成器的靈魂。 您可以得到屏幕的高度,並相應地設置標簽的字體。

CGFloat windowHeight = [UIApplication sharedApplication].delegate.window.frame.size.height;
label.font = [UIFont fontWithName:@"Font-Name" size:windowHeight / 10];

UILabel也有一些類似的問題。 我不知道它是否適用於UITextField。 沒有足夠的聲譽來發表評論,所以就在這里。 基本上:

  • 將字體大小設置為很大(例如:200)
  • 由於棄用,請使用minimumScaleFactor而不是minimumFontSize

請參考這里:

如何設置字體大小以填充UILabel高度?

動態更改字體大小-UILabel

uilabel不會自動縮小文本以適合標簽大小

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM