gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:22:51 27 4
gpt4 key购买 nike

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

这是它的样子: enter image description here

如您所见,底部和顶部重叠。所以,我一直在使用这段代码来尝试只在特定的边上添加边框:

    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)

这是它的样子:

enter image description here

您认为可能有什么问题?在添加边框之前,我一直等到标签有值。我只是通过使标签每边 10 点来设置宽度。

提前谢谢你,我知道这是一篇很长的文章!

最佳答案

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

cell.setNeedsLayout()
cell.layoutIfNeeded()

强制计算 UILabel 尺寸,导致在 addBorder 方法中获得预期值。

关于ios - Swift - 使用边框宽度和颜色设置标签边框有效,但在设置特定边时设置框架宽度关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42834187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com