在IOS 中,使用[UIFont familyNames]这个方法获取72种系统字体。
使用[UIFont fontWithName:@"Zapfino" size:18]这个方法为空间中的文字设置字体和字号。
可以通过for循环批量定义控件并设置属性。
以下程序获取系统72种字体并存储在一个数组中,有两种方法,一种是通过for循环拿到每一种字体并添加到可变数组中,另一种是直接把72种字体赋值给一个数组。
注:在页面控件较少的情况下选择手动创建每个控件,在控件数量较大且有规律排布的时候使用循环批量创建控件。可以通过获取硬件设备的分辨率进而让控件的尺寸自动适配设备。具体方式为:
//屏幕尺寸CGRect rect = [[UIScreen mainScreen] bounds];CGSize size = rect.size;CGFloat width = size.width;CGFloat height = size.height;NSLog(@"print %f,%f",width,height);//分辨率CGFloat scale_screen = [UIScreen mainScreen].scale;width*scale_screen,height*scale_screen
程序内容:
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//定义一个可变数组,用来存放所有字体NSMutableArray *fontarray = [NSMutableArray arrayWithCapacity:10];//遍历UI字体for (id x in [UIFont familyNames]) {NSLog(@"%@",x);[fontarray addObject:x];}//直接把字体存储到数组中NSArray *fontarrauy2 = [UIFont familyNames];NSLog(@"%@",fontarrauy2);//创建一个label,用来显示设定某种字体的字符串UILabel *mylab1 = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 50)];mylab1.font = [UIFont systemFontOfSize:20];mylab1.font = [UIFont fontWithName:@"Zapfino" size:18];mylab1.font = [UIFont fontWithName:[fontarray objectAtIndex:10] size:18];mylab1.text = @"HelloWorld";[self.view addSubview:mylab1];//新建一个可变数组,用来存放使用for循环批量创建的labelNSMutableArray *labarr = [NSMutableArray arrayWithCapacity:100];for (int x=0; x<24; x++) {for (int y=0; y<3; y++) {//循环创建72个label,每个label横向间距135-130=5,纵向间距30-28=2,UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(y*135+7, x*30+20, 130, 28)];lab.backgroundColor = [UIColor colorWithRed:0.820 green:0.971 blue:1.000 alpha:1.000];lab.text = @"HelloWorld";//将创建好的label加入到可变数组[labarr addObject:lab];}}//使用for循环给72个label的字体设置各种字体格式for (int i=0; i<72; i++) {UILabel *lab = [labarr objectAtIndex:i];NSString *fontstring = [fontarray objectAtIndex:i];lab.font = [UIFont fontWithName:fontstring size:18];[self.view addSubview:[labarr objectAtIndex:i]];}}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end
以上就是本文的全部内容,希望对大家的学习有所帮助。