IOS開發(fā)中使用UIFont設(shè)置字體及批量創(chuàng)建控件
在IOS 中,使用[UIFont familyNames]這個方法獲取72種系統(tǒng)字體。
使用[UIFont fontWithName:@"Zapfino" size:18]這個方法為空間中的文字設(shè)置字體和字號。
可以通過for循環(huán)批量定義控件并設(shè)置屬性。
以下程序獲取系統(tǒng)72種字體并存儲在一個數(shù)組中,有兩種方法,一種是通過for循環(huán)拿到每一種字體并添加到可變數(shù)組中,另一種是直接把72種字體賦值給一個數(shù)組。
注:在頁面控件較少的情況下選擇手動創(chuàng)建每個控件,在控件數(shù)量較大且有規(guī)律排布的時候使用循環(huán)批量創(chuàng)建控件??梢酝ㄟ^獲取硬件設(shè)備的分辨率進而讓控件的尺寸自動適配設(shè)備。具體方式為:
//屏幕尺寸 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
程序內(nèi)容:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 定義一個可變數(shù)組,用來存放所有字體
NSMutableArray *fontarray = [NSMutableArray arrayWithCapacity:10];
// 遍歷UI字體
for (id x in [UIFont familyNames]) {
NSLog(@"%@",x);
[fontarray addObject:x];
}
// 直接把字體存儲到數(shù)組中
NSArray *fontarrauy2 = [UIFont familyNames];
NSLog(@"%@",fontarrauy2);
// 創(chuàng)建一個label,用來顯示設(shè)定某種字體的字符串
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];
// 新建一個可變數(shù)組,用來存放使用for循環(huán)批量創(chuàng)建的label
NSMutableArray *labarr = [NSMutableArray arrayWithCapacity:100];
for (int x=0; x<24; x++) {
for (int y=0; y<3; y++) {
// 循環(huán)創(chuàng)建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";
// 將創(chuàng)建好的label加入到可變數(shù)組
[labarr addObject:lab];
}
}
// 使用for循環(huán)給72個label的字體設(shè)置各種字體格式
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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
iOS如何實現(xiàn)強制轉(zhuǎn)屏、強制橫屏和強制豎屏的實例代碼
本篇文章主要介紹了iOS如何實現(xiàn)強制轉(zhuǎn)屏、強制橫屏和強制豎屏的實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
MAC 系統(tǒng)安裝java并配置環(huán)境變量
這篇文章主要介紹了MAC 系統(tǒng)安裝java并配置環(huán)境變量的相關(guān)資料,需要的朋友可以參考下2017-03-03
解決iOS11圖片下拉放大出現(xiàn)信號欄白條的bug問題
這篇文章主要介紹了iOS11圖片下拉放大出現(xiàn)信號欄白條的bug問題,需要的朋友參考下吧2017-09-09

