背景
您好,我有一个带有自定义单元格的tableView,如下图所示。
目标
我的目标是使绿色正方形变为圆形。我尝试使用下面的代码执行此操作。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ColorKeyCell", for: indexPath) as! ColorKeyCell
cell.colorCircleLabel.layer.cornerRadius = (cell.frame.size.width * 0.5)
cell.colorCircleLabel.layer.masksToBounds = true
cell.colorCircleLabel.backgroundColor = colorKey[indexPath.row].color
cell.exampleLabel.attributedText = colorKey[indexPath.row].basicExample
cell.explanationLabel.text = colorKey[indexPath.row].explanation
return cell
}
问题
如果我注释掉cell.colorCircleLabel.layer.masksToBounds = true
,将出现绿色框,但不是圆形。如果我取消注释,该框将完全消失。不仅如此,如果我仅在其中一个单元格上使用cell.colorCircleLabel.layer.masksToBounds = true
,则在填充tableView时,也会使其他一些单元格的绿色框也消失。我在堆栈溢出中做了很多查找,但是无法解决问题。有人说您需要在layoutIfNeeded()
中调用viewDidLayoutSubviews
。这些示例与我的案例不同,但是我认为我尝试正确,但是没有用。
我在想,也许它与水平stackView设置有关,或者与stackView中标签的拥抱或压缩优先级有关,但并不确定。以下是这些图片,以防万一。
绿箱优先级:拥抱251,压缩750
标签优先级:拥抱250压缩750
声音按钮优先级:拥抱251,压缩750
任何建议都非常感谢。谢谢!
更改此行:
cell.colorCircleLabel.layer.cornerRadius = (cell.frame.size.width * 0.5)
收件人:
cell.colorCircleLabel.layer.cornerRadius = cell.colorCircleLabel.frame.width/2
OR
cell.colorCircleLabel.layer.cornerRadius = cell.colorCircleLabel.frame.height/2
尝试使用clipsToBounds = true
cell.colorCircleLabel.layer.cornerRadius = (cell.colorCircleLabel.bounds.size.height / 2)
cell.clipsToBounds = true
这应该工作。