如何为UIButton扩展字体大小设置方法,适配选中/普通状态?
Absolutely! You can absolutely extend UIButton to add methods for setting font sizes (or custom font styles) just like you did with background colors. This is a fantastic way to keep your code clean and DRY (Don’t Repeat Yourself) when you need to configure multiple buttons consistently.
Here’s how to implement it:
First, add this extension to your project:
import UIKit extension UIButton { // Basic method to set font size (with optional bold toggle) func setTitleFontSize(_ size: CGFloat, isBold: Bool = false) { let targetFont = isBold ? UIFont.boldSystemFont(ofSize: size) : UIFont.systemFont(ofSize: size) titleLabel?.font = targetFont } // Advanced method: set different fonts for specific control states func setTitleFont(_ font: UIFont, for state: UIControl.State) { // Get the current title text and color for the state to preserve them guard let titleText = title(for: state), let titleColor = titleColor(for: state) else { return } let attributedTitle = NSAttributedString( string: titleText, attributes: [ .font: font, .foregroundColor: titleColor ] ) setAttributedTitle(attributedTitle, for: state) } }
How to use these methods:
For a simple, state-agnostic font size setup (great if all states use the same font):
// Set bold 16pt font for a button yourButton.setTitleFontSize(16, isBold: true) // Set regular 14pt font for another button anotherButton.setTitleFontSize(14)For state-specific font configurations (e.g., different font when the button is selected):
// Normal state: regular 16pt statefulButton.setTitleFont(UIFont.systemFont(ofSize: 16), for: .normal) // Selected state: bold 18pt statefulButton.setTitleFont(UIFont.boldSystemFont(ofSize: 18), for: .selected)
Why this works:
Just like your setBackgroundColor(_:forState:) extension, this approach leverages UIButton’s existing properties. The basic method directly updates the titleLabel?.font (which applies to all states unless overridden), while the state-specific method uses attributed titles to apply different fonts per state—similar to how background colors are set per state.
This will save you tons of repetitive code when configuring multiple buttons across your app!
内容的提问来源于stack exchange,提问作者Arinjay

