为TableView单元格添加自定义字体遇报错,求技术解决方案
Hey there, let's get that custom font working in your TableView cell and squash that compile error first!
First: Fix the Immediate Compile Error
The syntax error you're hitting is super straightforward—you messed up the argument list for the UIFont initializer. Your code has an extra comma that doesn't belong:
cell.nameLabel.font = UIFont(name: "USIS 1949", size, 25)
That's invalid Swift syntax. The UIFont initializer only takes two parameters: the font name and the size. Fix it like this:
cell.nameLabel.font = UIFont(name: "USIS 1949", size: 25)
Next: Ensure the Font is Properly Imported & Configured
Even after fixing the syntax, the font might still not show up if you skipped critical setup steps. Let's walk through what you might have missed:
Add the font file to your project correctly:
Drag your.ttf/.otffont file into Xcode, and make sure you check the box for your app target in the "Add to targets" prompt. Double-verify by selecting the font file in Xcode and checking the target membership in the right sidebar.Update your Info.plist:
Add theFonts provided by application(raw key:UIAppFonts) array to your Info.plist. For each font, add a string entry with the exact filename (including the extension, e.g.,USIS1949.ttf). Capitalization and spelling matter here—don't guess!Find the actual internal font name:
This is the most common gotcha: font filenames often don't match the internal name iOS uses. For example, your file might beUSIS1949.ttfbut its real name isUSIS-1949.To uncover the correct name, run this snippet once in your app (like in your view controller's
viewDidLoad) and check the console:for family in UIFont.familyNames.sorted() { let fontNames = UIFont.fontNames(forFamilyName: family) print("Font Family: \(family) | Available Fonts: \(fontNames)") }Look for your font in the output, then use that exact string in your
UIFontinitializer.
Final Check: Make Sure No Code Overrides the Font
Double-check your TableView cell setup:
- If you're using a storyboard/xib for the cell, ensure you haven't set a static font there that overrides your code-set font.
- Check if your cell's
awakeFromNib()orlayoutSubviews()methods reset the label's font behind the scenes.
Corrected Full Code Example
Here's your code with the syntax fix and a reminder to use the correct font name:
let question = QuestionController.questionsList[questionIndex] cell.nameLabel.text = question.answers?[indexPath.row] cell.nameLabel.numberOfLines = 0 cell.nameLabel.lineBreakMode = .byWordWrapping // Replace with the actual font name you found from the console output cell.nameLabel.font = UIFont(name: "Actual-USIS-1949-Name", size: 25)
内容的提问来源于stack exchange,提问作者sheishistoric

