【问题标题】:Swift 5 : Resizing a button according to titleLabel length with paddingSwift 5:根据titleLabel长度调整按钮的大小和填充
【发布时间】:2021-11-27 14:20:37
【问题描述】:

我有一个水平的UIStackView,其中包含一个UILabel 和一个UIButton

我的UILabel 正确地拟合并包裹了UIStackView 的中间,但问题是我的UIButton 中间的内容被截断或没有填充。

我要做的是:

        let container = UIStackView()
        self.addSubview(container)
        container.addArrangedSubview(debateName)
        container.addArrangedSubview(debateButton)
        container.axis = .horizontal
        container.distribution = .equalSpacing
        container.alignment = .center
        container.spacing = 15
        container.isLayoutMarginsRelativeArrangement = true
        container.layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        container.isUserInteractionEnabled = true
        
        container.addBorder(hexString: SettingsProvider.sharedInstance.borderBoxColor, width: 0.2)
        container.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.left.equalTo(self)
            make.right.equalTo(self)
            make.height.greaterThanOrEqualTo(100)
        }
        
        myLabel.numberOfLines = 0

        myButton.setTitle(NSLocalizedString(self.textKey, comment: ""), for: .normal)
        myButton.uppercased()
        myButton.layer.cornerRadius = 6
        myButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10)
        myButton.sizeToFit()
        myButton.addBorder(hexString: SettingsProvider.sharedInstance.borderBoxColor, width: 0.2)
        myButton.addShadow(offset: CGSize.init(width: 0, height: 1), color: UIColor.init(hexString: SettingsProvider.sharedInstance.borderBoxColor), radius: 4, opacity: 0.35)

我唯一能做的就是删除contentEdgeInsets(),这样我的内容就不会被截断,但我会丢失填充:

有没有办法把这两个要求结合起来?

【问题讨论】:

  • 我发现我可以减少 UIStackView 中元素之间的间距,但这更像是一种“技巧”而不是真正的解决方案。

标签: ios swift uibutton uistackview


【解决方案1】:

几件事...

  • 在您的堆栈视图中,设置.distribution = .fill 而不是.equalSpacing。您只有两个排列的子视图(只有一个空格)
  • 你不应该需要myButton.sizeToFit()

将此行添加到您的按钮设置中:

myButton.setContentCompressionResistancePriority(.required, for: .horizontal)

这应该可以防止您的按钮压缩/截断其标签。

【讨论】:

  • 运行良好。谢谢
猜你喜欢
  • 2021-12-11
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 2013-12-06
  • 2011-05-07
  • 2015-08-28
  • 1970-01-01
相关资源
最近更新 更多