我根据这个答案创建了扩展:
How to add a border just on the top side of a UIView
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
//https://stackoverflow.com/questions/17355280/how-to-add-a-border-just-on-the-top-side-of-a-uiview
let border = CALayer()
switch edge {
case UIRectEdge.Top:
border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness)
break
case UIRectEdge.Bottom:
border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness)
break
case UIRectEdge.Left:
border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame))
break
case UIRectEdge.Right:
border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame))
break
default:
break
}
border.backgroundColor = color.CGColor;
self.addSublayer(border)
}
}
但在Ipad中,我只看到70%的边框宽度:
我尝试将帧更改为边界,但它也没有用.
最佳答案 添加边框后调整视图的大小.你在viewDidLoad()方法中添加边框吧?尝试在viewDidAppear()方法中添加边框:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
yourView.layer.addBorder(UIRectEdge.Top, color: UIColor.redColor(), thickness: 0.5)
}
从中移动添加图层
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}
至
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.addBorder(UIRectEdge.Top, color: UIColor.redColor(), thickness: 0.5)
}