我有一个UIStackView,我试图添加2个标签作为子标签。当我使用addArrangedSubview添加它们时,视图中没有任何渲染,但是当我仅使用addSubview时,两个标签都渲染(尽管不在我想要的位置)。我在做什么错?
import UIKit
class RepCounterView : UIView {
var count : Int = 0
lazy var repCountLabel: UILabel = {
let repCountLabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: 120, height: 120))
repCountLabel.textColor = UIColor.white
repCountLabel.font = UIFont.systemFont(ofSize: 100)
repCountLabel.text = String(count)
repCountLabel.textAlignment = .center
return repCountLabel
}()
lazy var repsLabel: UILabel = {
let repsLabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: 120, height: 120))
repsLabel.textColor = UIColor.white
repsLabel.font = UIFont.systemFont(ofSize: 10)
repsLabel.text = repCountLabel.text == "1" ? "rep" : "reps"
return repsLabel
}()
lazy var stackView : UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
return stackView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
override func draw(_ rect: CGRect) {
self.layer.cornerRadius = self.bounds.size.width / 2
}
func setup() {
self.clipsToBounds = true
self.addSubview(self.stackView)
// This is where .addSubview works, but this doesn't
self.stackView.addArrangedSubview(repCountLabel)
self.stackView.addArrangedSubview(repsLabel)
}
}
您的更新代码,
lazy var stackView : UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.alignment = .fill
return stackView
}()
func setup() {
self.clipsToBounds = true
self.addSubview(self.stackView)
// This is where .addSubview works, but this doesn't
self.stackView.addArrangedSubview(repCountLabel)
self.stackView.addArrangedSubview(repsLabel)
stackView.widthAnchor.constraint(equalToConstant: 200).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
lazy var stackView : UIStackView = {
let stack = UIStackView(arrangedSubviews: [repCountLabel, repsLabel])
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
替换您的stackview代码和注释
self.stackView.addArrangedSubview(repCountLabel)
self.stackView.addArrangedSubview(repsLabel)
这些代码。这应该为您工作。如果没有,请尝试为您的stackview或高度和宽度提供锚点。