Kex*_*Kex 3 uiview uilabel ios swift uistackview
我在自定义视图上获取内容拥抱时遇到问题。我有以下代码:
pillView.setContentHuggingPriority(.required, for: .horizontal)
pillView.setContentCompressionResistancePriority(.required, for: .horizontal)
dateLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
dateLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
Run Code Online (Sandbox Code Playgroud)
我将这两个视图添加到堆栈视图中:
let dateStackView = UIStackView(arrangedSubviews: [pillView, dateLabel])
结果是这样的:
LIVE NOW 视图应该包含其内容。它的定义如下:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
不知道为什么它在堆栈视图中不会拥抱内容。有任何想法吗?非常感谢对此的一些指示。谢谢!
Don*_*Mag 17
在您的函数中添加这些行PillView init(...):
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .horizontal)
Run Code Online (Sandbox Code Playgroud)
然后,您不需要为您的pillView或dateLabel实例设置这些属性。
| 归档时间: |
|
| 查看次数: |
9195 次 |
| 最近记录: |