gpt4 book ai didi

ios - 内容拥抱优先级不适用于 UIStackView 中的自定义 View 和标签

转载 作者:行者123 更新时间:2023-12-05 08:22:06 32 4
gpt4 key购买 nike

我无法在自定义 View 上使用内容拥抱。我有以下代码:

pillView.setContentHuggingPriority(.required, for: .horizontal)
pillView.setContentCompressionResistancePriority(.required, for: .horizontal)
dateLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
dateLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

我将这两个 View 添加到堆栈 View 中:

让 dateStackView = UIStackView(arrangedSubviews: [pillView, dateLabel])

结果是这样的:

enter image description here

LIVE NOW View 应该包含它的内容。它是这样定义的:

final class PillView: UIView {

private enum Constants {
static let radius: CGFloat = 4.0
static let labelInsets = UIEdgeInsets(horizontal: 8.0, vertical: 4.0)
}

enum Config {
case attention

var font: UIFont {
switch self {
case .attention: return Font.caption
}
}
var textColor: UIColor {
switch self {
case .attention: return .white
}
}
var backgroundColor: UIColor {
switch self {
case .attention: return Theme.red100
}
}
}

// MARK: - Properties

private let config: Config

// MARK: - Initializers

init(text: String, config: Config = .attention) {
self.config = config
super.init(frame: .zero)

backgroundColor = config.backgroundColor
clipsToBounds = true
layer.cornerRadius = Constants.radius

let label = UILabel()
label.font = config.font
label.textColor = config.textColor
label.text = text

addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: topAnchor, constant: Constants.labelInsets.top),
label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -Constants.labelInsets.bottom),
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.labelInsets.left),
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.labelInsets.right)
])
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

不确定为什么在堆栈 View 中它不会包含内容。有任何想法吗?真的很感激这方面的一些建议。谢谢!

最佳答案

将这些行添加到您的 PillView init(...) 函数中:

label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .horizontal)

然后您不需要为您的 pillViewdateLabel 实例设置这些属性中的任何一个。

关于ios - 内容拥抱优先级不适用于 UIStackView 中的自定义 View 和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65228741/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com