无法在Swift、UIKit中以编程方式在UIView中添加UILabel
//
// GlanceTableViewCell.swift
//
// Created by Shivacharan Reddy on 23/03/23.
//
import UIKit
class GlanceTableViewCell: UITableViewCell {
static let identifier = "GlanceTableViewCell"
private let glanceView: UIView = {
let view = UIView()
view.backgroundColor = .gray
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let mainLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 15, weight: .bold)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .label
label.backgroundColor = .white
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(glanceView)
glanceView.addSubview(mainLabel)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
glanceView.widthAnchor.constraint(equalToConstant: contentView.bounds.width - 10).isActive = true
glanceView.heightAnchor.constraint(equalToConstant: contentView.bounds.height - 10).isActive = true
glanceView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
glanceView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
mainLabel.leadingAnchor.constraint(equalTo: glanceView.leadingAnchor, constant: 5).isActive = true
mainLabel.topAnchor.constraint(equalTo: glanceView.topAnchor, constant: 5).isActive = true
mainLabel.widthAnchor.constraint(equalToConstant: glanceView.bounds.width / 2).isActive = true
mainLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
}
我想在glanceView
中添加mainLabel
,它的类型是UIView
,但是当我运行代码时,我无法看到mainLabel
,它甚至不可见。我在这里做错了什么?
1条答案
按热度按时间pu82cl6c1#
您将
glanceView
的高度与当前为零的contentView.bound
相关联。此外,glanceView的宽度为0,所以标签宽度将为零,这是因为glanceView不知道它的宽度,因为在您的其他约束中,您没有将标签的前导和尾随挂钩到它的边界,此外,即使您设置了上述约束,也还很早就要求它的边界
所以在这种情况下,您需要将它与ContentView宽度关联
要将代码重构为