萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 點擊按鈕動態調整 UILabel 字體大小示例

通過按鈕交互動態修改標籤字體大小,是學習 iOS 視圖屬性更新的入門案例。

完整實現代碼

1. 創建並配置 UILabel

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(135, 290, 200, 35)];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.textAlignment = NSTextAlignmentCenter;
    
    // 初始字體
    self.label.font = [UIFont fontWithName:@"Arial-BoldMT" size:16];
    self.label.text = [NSString stringWithFormat:@"%.0f", self.slider.value];
    
    [self.view addSubview:self.label];
}

2. 按鈕點擊修改字體

- (IBAction)buttonPressed:(id)sender {
    // 放大字體
    self.label.font = [UIFont fontWithName:@"Arial-BoldMT" size:25];
    
    // 可選:配合動畫
    [UIView animateWithDuration:0.2 animations:^{
        self.label.transform = CGAffineTransformMakeScale(1.1, 1.1);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            self.label.transform = CGAffineTransformIdentity;
        }];
    }];
}

進階:Slider 實時調整字體大小

- (IBAction)sliderValueChanged:(UISlider *)sender {
    CGFloat fontSize = 12 + sender.value * 36; // 12~48pt
    self.label.font = [UIFont systemFontOfSize:fontSize weight:UIFontWeightBold];
    self.label.text = [NSString stringWithFormat:@"%.0f pt", fontSize];
}

關鍵知識點

  • UIFont 不可變,需重新賦值 label.font 才能生效。
  • 字體名稱需精確:@"Arial-BoldMT"、@"PingFangSC-Semibold"、@"HelveticaNeue-Bold" 等,可用 [UIFont familyNames] 遍歷系統字體。
  • 動態字體 (Dynamic Type) 支持:[UIFont preferredFontForTextStyle:UIFontTextStyleBody] 尊重用戶系統字體大小設置。
  • 性能:頻繁修改字體會觸發佈局重算,複雜界面建議節流或使用 CATextLayer。

簡單幾行代碼,掌握視圖屬性動態更新的核心模式。

copyright © 萬盛學電腦網 all rights reserved