閱讀之前攻谁,先來(lái)欣賞一張圖片
meng
1、言歸正傳弯予,改變字號(hào)可以有兩種方法戚宦,一種是給UIFont添加分類(lèi),一種是給UILabel和UIButton添加分類(lèi)锈嫩,在UILabel加載的時(shí)候改變?cè)O(shè)置字號(hào)受楼,下面就分別介紹這兩種方法的實(shí)現(xiàn)
1.1 首先介紹給UIFont添加分類(lèi)的方法
The first step:創(chuàng)建UIFont的分類(lèi)垦搬,如下圖
選擇Objective-c File
second:命名
命名為Setting
2、UIFont+Setting.h 下
創(chuàng)建一個(gè)方法
#import <UIKit/UIKit.h>
@interface UIFont (Setting)
// 設(shè)置字體的方法艳汽,代替系統(tǒng)的systemFontOfSize
+ (UIFont *)setFontWithSize:(CGFloat)size;
@end
UIFont+Setting.m下
#import "UIFont+Setting.h"
@implementation UIFont (Setting)
+ (UIFont *)setFontWithSize:(CGFloat)size{
// 取出存在本地的字號(hào)
CGFloat fontSize = [[NSUserDefaults standardUserDefaults] floatForKey:@"fontSize"];
CGFloat fontS = 2 * fontSize * size;
UIFont *myFont = [UIFont systemFontOfSize:fontS+size];
return myFont;
}
@end
3猴贰、在設(shè)置界面,創(chuàng)建一個(gè)滑動(dòng)控制開(kāi)關(guān)(UISlider)用于滑動(dòng)控制字號(hào)
SettingViewController.h
#import <UIKit/UIKit.h>
@interface SettingViewController : UIViewController
@end
SettingViewController.m
#import "SettingViewController.h"
#import "UIFont+Setting.h"
@interface SettingViewController (){
UISlider *slider; // 滑動(dòng)按鈕
UILabel * testLabel; // 測(cè)試label
}
@end
@implementation SettingViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// 設(shè)置頁(yè)面的搭建
[self setupUI];
}
- (void)setupUI{
// 滑動(dòng)按鈕的設(shè)置
slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 30)];
[self.view addSubview:slider];
[slider addTarget:self action:@selector(valueChange) forControlEvents:UIControlEventValueChanged];
slider.value = [[NSUserDefaults standardUserDefaults] floatForKey:@"fontSize"];
// 測(cè)試字體的設(shè)置
testLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 100)];
testLabel.text = @"這是測(cè)試字體";
testLabel.font = [UIFont setFontWithSize:10];
testLabel.textAlignment = NSTextAlignmentCenter;
testLabel.backgroundColor = [UIColor whiteColor];
[self.view addSubview:testLabel];
}
- (void)valueChange{
// 改變字號(hào)河狐,將字號(hào)存在本地
[[NSUserDefaults standardUserDefaults] setFloat:slider.value forKey:@"fontSize"];
testLabel.font = [UIFont setFontWithSize:10];
button.titleLabel.font = [UIFont setFontWithSize:8];
// 這里其實(shí)可以用通知米绕,本文就不介紹使用通知的方法了,
// [[NSNotificationCenter defaultCenter] postNotificationName:@"changeFont" object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
3.1 如圖馋艺,設(shè)置頁(yè)面的效果圖如下
設(shè)置頁(yè)面的效果圖
滑動(dòng)調(diào)節(jié)按鈕即可調(diào)節(jié)字體大小栅干,下圖為字號(hào)最大時(shí),其他頁(yè)面的效果圖捐祠,至此碱鳞,用給UIFont添加分類(lèi)的方法,實(shí)現(xiàn)全局調(diào)節(jié)字號(hào)即可實(shí)現(xiàn)了
主頁(yè)的效果圖
接下來(lái)還有一種全局改變字號(hào)的方法踱蛀,將在下一篇文章中介紹
iOS 全局改變字號(hào)(二)http://www.reibang.com/p/9f7ebb232bef