首页 > 解决方案 > 如何在 UITableView 上使用显示字体设置 UIFont 系列和名称?

问题描述

我尝试了这段代码并崩溃了它说打开它。那么我如何在左侧单元格上显示带有显示和名称的字体。

结果代码:

import UIKit

 class ViewController: UIViewController {

let names = UIFont.familyNames.sorted()


@IBOutlet weak var FontTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

然后我添加代码来设置带有名称的显示字体。然后这是崩溃了。

}

 extension ViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    names.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cells = FontTableView.dequeueReusableCell(withIdentifier: "Cells")
    

    
    for family in UIFont.familyNames.sorted() {
      
        let names = UIFont.fontNames(forFamilyName: family)
        
        cells?.textLabel?.text = ("Family: \(family)")
        
        cells?.detailTextLabel?.text = ("Family: \(names)")
    }
    
    
    return cells!
}



}

标签: swiftuitableviewfonts

解决方案


我不知道你要在一行中显示什么。在您的代码 cellForRowAt 中,每一行都将运行循环。我猜你不应该使用循环,而是使用数据源名称。此外,fontNames 也是一个字符串数组。因此,根据您的要求(可能是第一个),分配给 detailsLabel。

       let family = names[indexPath.row] 
        
        let fontNames = UIFont.fontNames(forFamilyName: family)
        
        cells?.textLabel?.text = ("Family: \(family)")
        
        cells?.detailTextLabel?.text = ("Family: \(fontNames)")
    

推荐阅读