我试图在我的标签周围放置边框,使它们不重叠。这是我正在使用的代码:cell.jobAddress.layer.borderColor =
`cell.jobAddress.layer.borderColor = UIColor.black.cgColor
cell.jobAddress.layer.borderWidth = 2
cell.jobPlaceBid.layer.borderColor = UIColor.black.cgColor
cell.jobPlaceBid.layer.borderWidth = 2
`
如您所见,底部和顶部重叠。所以,我一直在使用此代码尝试仅向特定方添加边框:
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case UIRectEdge.top:
border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
break
case UIRectEdge.right:
border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
然后执行它:
cell.jobAddress.layer.addBorder(edge: UIRectEdge.left, color: UIColor.black, thickness: 2)
cell.jobAddress.layer.addBorder(edge: UIRectEdge.right, color: UIColor.black, thickness: 2)
cell.jobAddress.layer.addBorder(edge: UIRectEdge.top, color: UIColor.black, thickness: 2)
cell.jobAddress.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.black, thickness: 2)
cell.jobPlaceBid.layer.addBorder(edge: UIRectEdge.left, color: UIColor.black, thickness: 2)
cell.jobPlaceBid.layer.addBorder(edge: UIRectEdge.right, color: UIColor.black, thickness: 2)
cell.jobPlaceBid.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.black, thickness: 2)
这是这样的:
您认为可能出错?在添加边框之前,我等到标签有值。我只是通过使标签从每一侧10点来设置宽度。
提前谢谢,我知道这是一篇很长的帖子!
答案 0 :(得分:1)
在您拨打addBorder
时,自动布局没有时间布置您的观看次数。
cell.setNeedsLayout()
cell.layoutIfNeeded()
强制计算UILabel尺寸,导致预期值进入addBorder
方法。
答案 1 :(得分:0)
@RaheshkumarR在评论中回答了这个问题,我只是在其他人遇到问题时将其发布在此处以供查看。解决方案是使用cell.mylabel.setNeedsLayout()和cell.mylabel.layoutIfNeeded()。
我希望这有帮助!