Teach you how to set various fonts in iOS projects

Source: Internet
Author: User

There are many ways to set up fonts in iOS development, so here are three more common ways to introduce them

1. Use the fonts provided by the system default

The default font provided by the system is primarily the font provided in Uifont, which uses the following code:

Fontlabel.font = [Uifont fontwithname:@ "Marion" size:+];

or set the font properties through a font-specific dictionary

/*uifontdescriptorfamilyattribute: Sets the font family name Uifontdescriptornameattribute: Sets the font name of the font uifontdescriptorsizeattr Ibute: Set Font size uifontdescriptormatrixattribute: Set font deformation*/Uifontdescriptor*attributefontdescriptor =[uifontdescriptor fontdescriptorwithfontattributes: @{uifontdescripto Rfamilyattribute:@"Marion", Uifontdescriptornameattribute:@"Marion-regular", Uifontdescriptorsizeattribute: @40.0, Uifontdescriptormatrixattribute:[nsvalue valuewithcgaffinetransfor M:cgaffinetransformmakerotation (M_1_pi*1.5)                                                                                    ]}]; Fnotlabel.font= [Uifont fontwithdescriptor:attributefontdescriptor size:0.0];

The font family name and font name can be obtained in the following ways

NSLog (@ "familynames:%@", [Uifont familynames]);

Both of these methods can be used to set the font for the label, but all are only for English numerals and are not valid for Chinese. There are two other ways to change the Chinese font to use the following

2. Dynamically download fonts

IOS6 after the Apple began to support the dynamic download of Chinese fonts have been used in the application to display the demand for personalized fonts, because the download needs to use the name is the PostScript name, you need to use the Mac's own app "font book" to get the PostScript name of the corresponding font. The following shows the PostScript name of the doll body -complex font from the font book

The specific code will not be introduced, you can refer to the relevant documents provided by Apple: https://developer.apple.com/library/ios/samplecode/DownloadFont/Listings/ Downloadfont_viewcontroller_m.html#//apple_ref/doc/uid/dts40013404-downloadfont_viewcontroller_ M-dontlinkelementid_6

Or you can refer to Mr. Tang Qi's blog For more detailed introduction: http://blog.devtang.com/blog/2013/08/11/ios-asian-font-download-introduction/

Here is my research after the test demo, to provide you with reference:

- (void) Asynchronouslysetfontname: (NSString *) fontname{Uifont* Afont = [Uifont fontwithname:fontname size: -]; //If The font is already downloaded    if(Afont && ([afont.fontname compare:fontname] = = Nsorderedsame | | [Afont.familyname compare:fontname] = =nsorderedsame)) {        //Go ahead and display the sample text._flabelview.text =@"Welcome to view my blog"; _flabelview.font= [Uifont fontwithname:fontname size: -]; return; }        //Create A dictionary with the font ' s PostScript name.Nsmutabledictionary *attrs =[Nsmutabledictionary dictionarywithobjectsandkeys:fontname, Kctfontnameattribute, nil]; //Create A new font descriptor reference from the attributes dictionary.Ctfontdescriptorref desc =ctfontdescriptorcreatewithattributes ((__bridge cfdictionaryref) attrs); Nsmutablearray*descs = [Nsmutablearray arraywithcapacity:0]; [Descs addobject: (__bridgeID) desc];        Cfrelease (DESC); __block BOOL errorduringdownload=NO; //Start processing the font descriptor. //This function returns the immediately, but can potentially take a long time to process. //The progress is notified via the callback block of Ctfontdescriptorprogresshandler type. //See CTFontDescriptor.h for the list of progress states and keys for Progressparameter dictionary.Ctfontdescriptormatchfontdescriptorswithprogresshandler ((__bridge cfarrayref) Descs, NULL, ^(ctfontdescriptormatchingstate State, Cfdictionaryref progressparameter) {//NSLog (@ "state%d-%@", State, progressparameter);                DoubleProgressvalue = [[(__bridge nsdictionary *) progressparameter Objectforkey: (ID) kctfontdescriptormatchingpercentage] doublevalue]; if(state = =Kctfontdescriptormatchingdidbegin) {Dispatch_async (Dispatch_get_main_queue (),^ {                //Show an activity indicatorNSLog (@"Begin Matching");        }); } Else if(state = =kctfontdescriptormatchingdidfinish) {Dispatch_async (Dispatch_get_main_queue (),^ {                //Remove the activity indicator//Display The sample text for the newly downloaded font_flabelview.text =@"Welcome to view my blog"; _flabelview.font= [Uifont fontwithname:fontname size: -]; //Log the font URL in the consoleCtfontref fontref = Ctfontcreatewithname ((__bridge cfstringref) FontName,0., NULL); Cfstringref Fonturl=Ctfontcopyattribute (Fontref, Kctfonturlattribute); NSLog (@"%@", (__bridge nsurl*) (Fonturl));                Cfrelease (Fonturl);                                Cfrelease (FONTREF); if(!errorduringdownload) {NSLog (@"%@ Downloaded", FontName);        }            }); } Else if(state = =kctfontdescriptormatchingwillbegindownloading) {Dispatch_async (Dispatch_get_main_queue (),^ {                //Show a progress barNSLog (@"Begin Downloading");        }); } Else if(state = =kctfontdescriptormatchingdidfinishdownloading) {Dispatch_async (Dispatch_get_main_queue (),^ {                //Remove the progress barNSLog (@"Finish Downloading");        }); } Else if(state = =kctfontdescriptormatchingdownloading) {Dispatch_async (Dispatch_get_main_queue (),^ {                //Use the progress bar to indicate the progress of the downloadingNSLog (@"Downloading%.0f%% complete", Progressvalue);        }); } Else if(state = =kctfontdescriptormatchingdidfailwitherror) {            //An error has occurred. //Get the error messageNserror *error = [(__bridge nsdictionary *) progressparameter Objectforkey: (ID) Kctfontdescriptormatchingerror]; if(Error! =Nil) {_errormessage=[error description]; } Else{_errormessage=@"ERROR MESSAGE is not available!"; }            //Set Our flagErrorduringdownload =YES; Dispatch_async (Dispatch_get_main_queue (),^{NSLog (@"Download Error:%@", _errormessage);        }); }        return(BOOL) YES;   }); }

Just call it in the appropriate place:

-(void) viewdidload {    [super Viewdidload];     // additional setup after loading the view, typically from a nib.    _flabelview = [[Uitextview alloc] Initwithframe:cgrectmake ( )];    [Self.view Addsubview:_flabelview];        [Self asynchronouslysetfontname: @" HANZIPENSC-W3 " ];    }

Here is the result after the run:

3. Introduction of external fonts

Now, whether it's a Windows font or an Android font, as long as it's in TTF format, or the TTC, OTF format provided by Apple, the iOS program supports inline. Specific practices:

Drag the font you want to download to your project first

Add a field to the info file

You can then use the method provided above [Uifont fontwithname:@ "mini-Mimi" Size:17] method to set this font in English, digital, or Chinese. can output [Uifont Familynames] detection has been added

You can also set this font for a label in Xib.

Download fonts on the web is not necessarily all can be used, the following provides some common fonts for everyone to download:

Link: http://pan.baidu.com/s/1c09Byec Password: m2e4

To get a more comprehensive font, you can also use the various font formats provided by Apple itself, or it can be obtained using the "font side" of the Mac app, for example:

Usage is the same as the downloaded font

Teach you how to set various fonts in iOS projects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.