如何让垂直UIStackView中的UIButton文本与UILabel文本左端对齐?
问题原因
UIButton在UIKit中默认自带左右内容内边距,仅设置contentHorizontalAlignment = .left只会让按钮文本在按钮自身的内容区域内左对齐,默认的左侧内边距会将文本整体向右偏移,因此会和上方无额外内边距的UILabel出现对齐偏差。
解决方案
方案1:清除按钮默认内边距
分系统版本选择对应代码即可:// iOS 15 及以上版本使用 Configuration 配置 var config = UIButton.Configuration.plain() config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0) self.selectPersonButton.configuration = config self.selectPersonButton.contentHorizontalAlignment = .left// 兼容iOS 15以下版本 self.selectPersonButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) self.selectPersonButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) self.selectPersonButton.contentHorizontalAlignment = .left方案2:手动偏移约束对齐
不需要修改按钮原有配置,仅调整约束即可:打印selectPersonButton.contentEdgeInsets.left获取按钮默认左侧内边距数值,将按钮的leading约束和上方UILabel的leading约束的偏移值设置为负的该数值即可,示例:let buttonLeftInset = selectPersonButton.contentEdgeInsets.left selectPersonButton.leadingAnchor.constraint(equalTo: topLabel.leadingAnchor, constant: -buttonLeftInset).isActive = true方案3:文本展示与点击事件分离
若需要保留按钮原有内边距保证点击热区大小,可以将按钮文本隐藏,额外新增一个UILabel放在按钮上层,让该label和上方UILabel左对齐,按钮本身仅负责响应点击事件,该方案对齐精度最高,无需适配系统版本差异。
内容的提问来源于stack exchange,提问作者tech_human
相关产品推荐
相关产品推荐

