标签框未正确停留在 `UICollectionViewCell` 中

label frame not stay Properly in `UICollectionViewCell`

我正在开发 UICollectionView 的自定义日历。 我想为今天的日期显示 label 的圆圈背景。

我在 uitableviewCell 中的代码:

let todayDate = Date().removeTimeStamp()
    self.lblDate.text = "\(String(describing: day))"
    if date == todayDate{
        lblDate.textColor = .white
        lblDate.layer.cornerRadius = lblDate.frame.width/2
        lblDate.layer.backgroundColor = UIColor.appOrange.cgColor
    }else if date < todayDate {
        lblDate.textColor = .lightGray
        lblDate.layer.backgroundColor = UIColor.white.cgColor
    }else{
        lblDate.textColor = .black
        lblDate.layer.backgroundColor = UIColor.white.cgColor
    }  

但我没有得到正确的 circle.see:

当我从 StoryBoard 更改 UICollectionViewCell 的大小时,圆的形状也会发生变化。

具有1:1纵横比约束的lable

怎样做才能得到合适的圈子??

谢谢!!

放在里面

func layoutSubviews()
{
    super.layoutSubviews()
    lblDate.layer.cornerRadius = lblDate.frame.width/2
    lblDate.clipsToBounds = true
}

你也可以创建全局函数:

extension UILabel {
func setRoundEdge() {
   let radius = self.frame.height/2
    self.layer.borderWidth = 0.3
    self.layer.masksToBounds = false
    self.layer.borderColor = UIColor.black.cgColor
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = true
}

}

问题是,当我们在正确完成布局之前访问标签框架时,我们得到了错误的框架。

解法:

您可以覆盖 UICollectionView class 的 layoutSubviews 方法。

func layoutSubviews() {
    super.layoutSubviews()
    lblDate.layer.cornerRadius = lblDate.frame.width/2
}