通過按鈕交互動態修改標籤字體大小,是學習 iOS 視圖屬性更新的入門案例。
- (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];
}
- (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;
}];
}];
}
- (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] 遍歷系統字體。[UIFont preferredFontForTextStyle:UIFontTextStyleBody] 尊重用戶系統字體大小設置。CATextLayer。簡單幾行代碼,掌握視圖屬性動態更新的核心模式。