Swift - 使用边框宽度和颜色设置标签边框是有效的,但在设置特定边时设置框架宽度关闭

Swift - Setting a label border using border width and color is working, but setting when setting a specific side the frame width is off

我试图在我的标签的某些边加上边框,这样它们就不会重叠。这是我使用的代码: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 点来设置宽度。

提前谢谢你,我知道这很长post!

@RaheshkumarR 在评论中回答了这个问题,我只是将它张贴在这里以供其他人 运行 解决问题时的可见性。解决方案是使用 cell.mylabel.setNeedsLayout() 和 cell.mylabel.layoutIfNeeded()。

希望对您有所帮助!

在您调用 addBorder 时,自动布局还没有时间对您的视图进行布局。

cell.setNeedsLayout()
cell.layoutIfNeeded()

强制计算 UILabel 尺寸,导致预期值进入 addBorder 方法。