最佳答案
Can I do it within the interface builder or do I have to do it programmatically?
您必须以编程方式执行此操作:定义 UIBezierPath
,将其用作 CAShapeLayer
的 path
,然后屏蔽 View 的使用此形状图层的图层。
@IBDesignable
class SlantedView: UIView {
@IBInspectable var slantHeight: CGFloat = 50 { didSet { updatePath() } }
private let shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 0
shapeLayer.fillColor = UIColor.white.cgColor // with masks, the color of the shape layer doesn’t matter; it only uses the alpha channel; the color of the view is dictate by its background color
return shapeLayer
}()
override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
private func updatePath() {
let path = UIBezierPath()
path.move(to: bounds.origin)
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY - slantHeight))
path.close()
shapeLayer.path = path.cgPath
layer.mask = shapeLayer
}
}
但通过将其设为 @IBDesignable
View ,您可以在 IB 中呈现它,这样您至少可以设计 UI,更清楚地了解最终产品的外观:
仅供引用,如果您确实使它可设计,他们建议您为您的可设计对象创建一个单独的框架目标(这样如果您在处理主项目时去 IB,渲染可设计 View 的能力不会受到影响因为您的主要项目可能不是稳定的、可编译的状态)。
关于ios - 创建具有倾斜边缘的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47292743/