使用UIButton.Configuration创建的UIButton图标尺寸适配问题
当使用UIButton.Configuration创建按钮时,直接设置button.imageView?.contentMode不会生效——因为Configuration模式下的图片渲染逻辑由UIButton.Configuration.ImageProperties控制,而非传统的imageView属性。
解决方法
- 在配置
UIButton.Configuration时,通过imageProperties.resizingMode设置图片的缩放模式 - 可选:若需要更精确控制图片大小,可设置
imageProperties.maximumSize限制图片的最大尺寸
修改后的完整代码
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let stackView1 = UIStackView() stackView1.translatesAutoresizingMaskIntoConstraints = false stackView1.distribution = .fill stackView1.alignment = .fill stackView1.heightAnchor.constraint(equalToConstant: 30).isActive = true let stackView2 = UIStackView() stackView2.translatesAutoresizingMaskIntoConstraints = false stackView2.distribution = .fill stackView2.alignment = .fill stackView2.heightAnchor.constraint(equalToConstant: 30).isActive = true view.addSubview(stackView1) view.centerXAnchor.constraint(equalTo: stackView1.centerXAnchor).isActive = true view.centerYAnchor.constraint(equalTo: stackView1.centerYAnchor).isActive = true view.addSubview(stackView2) view.centerXAnchor.constraint(equalTo: stackView2.centerXAnchor).isActive = true stackView2.topAnchor.constraint(equalTo: stackView1.centerYAnchor, constant: 80).isActive = true stackView1.addArrangedSubview(makeButton(backgroundColor: .red)) stackView1.addArrangedSubview(makeButton(backgroundColor: .blue)) stackView1.addArrangedSubview(makeButton(backgroundColor: .yellow)) stackView1.addArrangedSubview(makeButton(backgroundColor: .cyan)) stackView2.addArrangedSubview(makeButtonWithConfiguration(backgroundColor: .red)) stackView2.addArrangedSubview(makeButtonWithConfiguration(backgroundColor: .blue)) stackView2.addArrangedSubview(makeButtonWithConfiguration(backgroundColor: .yellow)) stackView2.addArrangedSubview(makeButtonWithConfiguration(backgroundColor: .cyan)) } func makeButton(backgroundColor: UIColor) -> UIButton { let button = UIButton() button.setImage(UIImage(named: "apple.png"), for: .normal) button.backgroundColor = backgroundColor button.imageView?.contentMode = .scaleAspectFit return button } func makeButtonWithConfiguration(backgroundColor: UIColor) -> UIButton { var configuration = UIButton.Configuration.plain() configuration.image = UIImage(named: "apple.png") configuration.contentInsets = .zero // 配置图片缩放模式,让图片适配按钮尺寸 configuration.imageProperties.resizingMode = .scaleAspectFit // 可选:限制图片最大尺寸,确保在按钮内完整显示 // configuration.imageProperties.maximumSize = CGSize(width: 24, height: 24) let button = UIButton(configuration: configuration) button.backgroundColor = backgroundColor button.translatesAutoresizingMaskIntoConstraints = false return button } }
原理说明
UIButton.Configuration将按钮的所有样式(包括图片、文本、间距等)封装在配置对象中,传统的imageView属性会被Configuration的设置覆盖。通过imageProperties.resizingMode可指定图片的缩放行为:
.scaleAspectFit:保证图片完整显示且适配按钮边界.scaleAspectFill:填满按钮但可能裁剪图片
可根据实际需求选择对应模式。

内容的提问来源于stack exchange,提问作者Petro Shm
相关产品推荐
相关产品推荐

