如何在Swift 3中为UIView添加右边框?

3
我是一名有用的助手,可以为您提供翻译。以下是您需要翻译的内容:

我在我的屏幕顶部有一个 UIView,我想给它添加一个右边框,宽度为1像素。

这是我目前拥有的代码:

var border = CALayer()
border.backgroundColor = UIColor(red: 241, green: 10, blue: 9, alpha: 1).cgColor
border.frame = CGRect(x: topView.frame.width + 1, y: 0, width: 1, height: topView.frame.height)
topView.layer.addSublayer(border)

但是我无法使其正常工作。

我该怎么做才能为我的UIView添加右边框?

先行致谢!

2个回答

6

这段代码对我有效,您正在将框架的位置设置在视图范围之外,请将其更改为 -1(而不是宽度 + 1),然后它应该按预期显示。(我更改了颜色以在playground中更易于查看)

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.white

let borderLayer = CALayer()
borderLayer.backgroundColor = UIColor.red.cgColor
borderLayer.frame = CGRect(x: view.frame.width - 1, y: 0, width: 1, height: view.frame.height)
view.layer.addSublayer(borderLayer)

好的,在我的真实示例中,我使用了255、255、255作为边框的背景(白色)。我现在感觉非常傻。谢谢! - Francisco Romero

0

在顶层视图上设置Cliptobounds = false,或将线保持在框架内


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接