首先,用XCode创建一个项目。 然后,拖入字体文件.ttf 或 .otf 到工程中,配置 Info.plist - Fonts provided by application, 然后在 Build Phases - Copy Bundle Resources 里增加字体; 再然后,开始编写代码。
代码如下: // // ViewController.swift // ChangeFont // // Created by luopan on 16/8/3. // Copyright © 2016年 Hust University. All rights reserved. //
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//用来显示的文字
var data = ["30 Days Swift 第二天", "这些字体特别适合打「奋斗」和「理想」", "谢谢「造字工房」,本案例不涉及商业使用", "使用到造字工房劲黑体,致黑体,童心体", "呵呵,再见? See you next Project", "微博 @FaderLOLer"]
//字体的名字
var fontNames = ["MFTongXin_Noncommercial-Regular", "MFJinHei_Noncommercial-Regular", "MFZhiHei_Noncommercial-Regular"]
//字体名字的编号
var fontRowIndex = 0
//按钮实例
@IBOutlet weak var ChangeFontBtn: UIButton!
//避免在一个界面中添加太多的Label,使用UITableView进行展示
@IBOutlet weak var FontTabview: UITableView!
//点击事件的监听
[@IBAction](http://my.oschina.net/u/866341) func OnClick(sender: UIButton) {
fontRowIndex = (fontRowIndex + 1) % 3
//刷新界面
FontTabview.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
//指定自身为协议实现类
FontTabview.dataSource = self
FontTabview.delegate = self
//打印字体,找到以后可以删除的测试代码
for family in UIFont.familyNames() {
for font in UIFont.fontNamesForFamilyName(family){
print(font)
}
}
}
//指定行高
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50
}
//整个界面只有一列
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//每一列的行数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
//每行的现实风格和里面子控件的风格设置
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = FontTabview.dequeueReusableCellWithIdentifier("FontCell", forIndexPath: indexPath)
let text = data[indexPath.row]
cell.textLabel?.text = text
cell.textLabel?.textColor = UIColor.blackColor()
cell.textLabel?.font = UIFont(name: self.fontNames[fontRowIndex], size: 16)
return cell
}
//下面两个方法完成了分割线顶头的效果
override func viewDidLayoutSubviews() {
FontTabview.separatorInset = UIEdgeInsetsZero
FontTabview.layoutMargins = UIEdgeInsetsZero
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
}
注意:新手一定要记得设置Cell的Identify.还有就是Info.plist编写。
}