UIButton plain样式修改文字后字体缩小问题求解
针对你遇到的Plain样式UIButton修改文字后字体自动缩小的问题,核心原因是使用UIButton.Configuration时,标题样式由配置统一管理,直接修改titleLabel的font会被配置覆盖,且Plain配置本身没有直接的font属性,需要通过以下两种方式正确设置字体:
方案1:直接使用富文本标题(AttributedTitle)
在配置中直接传入带字体属性的富文本,完全自定义标题样式:
func buttonConfiguration() -> UIButton.Configuration { var config: UIButton.Configuration = .plain() // 创建带指定字体的富文本 let attributedTitle = NSAttributedString( string: "Some button text", attributes: [.font: UIFont.systemFont(ofSize: 55)] ) // 将NSAttributedString转为AttributedString赋值给配置 config.attributedTitle = AttributedString(attributedTitle) return config }
方案2:通过文本属性转换器修改默认字体
如果想保留Plain样式的其他默认文本属性(如颜色、行高),仅修改字体大小,可以使用titleTextAttributesTransformer覆盖默认字体:
func buttonConfiguration() -> UIButton.Configuration { var config: UIButton.Configuration = .plain() config.title = "Some button text" // 转换器:接收默认文本属性,修改后返回 config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { defaultAttributes in var modifiedAttributes = defaultAttributes modifiedAttributes.font = UIFont.systemFont(ofSize: 55) return modifiedAttributes } return config }
补充说明
- 为什么直接设置
button.titleLabel?.font无效:当按钮使用Configuration时,系统会根据配置自动更新titleLabel的样式,手动修改的font会被配置的样式覆盖,必须通过配置本身定义字体。 - 切换到Default样式出现动画的原因:Default样式的UIButton自带默认的高亮/点击淡入淡出动画,而Plain样式是无装饰的基础按钮,无默认动画。
内容的提问来源于stack exchange,提问作者Rayce Miller
相关产品推荐
相关产品推荐

