You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Swift Playground中如何修改UIButton的文字字体?

如何在Playground中修改UIButton的文字字体?

嘿,我来帮你搞定这个问题!要修改UIButton上文字的字体,核心是给按钮的titleLabel属性设置font值就行。下面是具体的实现步骤和修改后的完整代码:

步骤说明

  • UIButton的文字样式是通过它的titleLabel来控制的,我们可以直接给这个标签指定字体
  • 你可以选择使用系统自带字体,或者导入自定义字体来使用

修改后的完整代码

import UIKit
import PlaygroundSupport

// 创建按钮实例
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 375, height: 133.4))
button.backgroundColor = .red
button.setTitle("Test", for: .normal)

// 设置按钮文字字体(两种方式可选)
// 方式1:使用系统字体,指定字号和字重
button.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: .bold)

// 方式2:使用自定义字体(需先将字体文件添加到Playground资源中)
// button.titleLabel?.font = UIFont(name: "YourCustomFontFamilyName", size: 24)

// 将按钮添加到Playground预览视图,方便查看效果
PlaygroundPage.current.liveView = button

注意事项

  • titleLabel是可选类型,所以我们用?来安全访问
  • 如果使用自定义字体,记得把字体文件(比如.ttf或.otf)拖进Playground的资源目录,并且确保字体名称和你在代码里写的一致(可以通过打印UIFont.familyNames来查看所有可用字体)

内容的提问来源于stack exchange,提问作者Grazia Bo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:42:59