Swift UICollectionViewCell UIlabel issue



我正在写一个日历,每天都是一个单元格,每个单元格在contentView中都有一个圆润的UILabel,但我不知道为什么每个单元格上都有黑色的小边框日历图片

In 3d View 3d preview

类CalendarCell: UICollectionViewCell {

static var identifier: String = "DayCell"
let dayLabel: UILabel = UILabel()

override init(frame: CGRect) {
super.init(frame: frame)
self.setUpUI()
self.contentView.addSubview(dayLabel)
}
private func setUpUI() {
dayLabel.text = nil
dayLabel.sizeToFit()
dayLabel.backgroundColor = .white
//dayLabel.layer.borderWidth = 0.5

dayLabel.textColor = .black
dayLabel.textAlignment = .center
dayLabel.clipsToBounds = true

}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
dayLabel.frame = self.contentView.frame
dayLabel.layer.cornerRadius = dayLabel.frame.width / 2
}
override func prepareForReuse() {
super.prepareForReuse()
setUpUI()
}

我不确定是什么原因导致了这个问题,但我很确定你可以修复它,并通过改变你的代码来实现相同的行为:

let collectionViewCellWidth: CGFLoat = 150 // or whatever you want. You'd define this in the file with your custom flow layout or wherever your give the cell size to the collectionView.
class CalendarCell: UICollectionViewCell {
static let identifier = "DayCell" // type inference doesn't need the annotations on these two
let dayLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
private func setUpUI() {
contentView.layer.cornerRadius = collectionViewCellWidth / 2
contentView.clipsToBounds = true
contentView.backgroundColor = .white // or orange, whatever
dayLabel.text = nil
dayLabel.backgroundColor = .white
//dayLabel.layer.borderWidth = 0.5

dayLabel.textColor = .black
dayLabel.textAlignment = .center
dayLabel.translatesAutoresizingMaskIntoConstraints = false

contentView.addSubview(dayLabel)
NSLayoutConstraint.activate([
dayLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
dayLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//override func layoutSubviews() {
//    dayLabel.frame = self.contentView.frame
//    dayLabel.layer.cornerRadius = dayLabel.frame.width / 2
//}

// also as your code currently is, you don't do anything in your setup function that needs to be redone when a cell is dequeued for reuse. Unless you were setting some unique information for a cell like its color or text. Just FYI
override func prepareForReuse() {
super.prepareForReuse()
setUpUI()
} 
}

最新更新