答案 0 :(得分:2)
我可以在界面构建器中执行此操作,还是必须以编程方式执行此操作?
您必须以编程方式执行此操作:定义UIBezierPath
,将其用作path
的{{1}},然后使用此屏蔽视图的图层形状层。
CAShapeLayer
但是通过将其设为@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
}
}
视图,您可以在IB中呈现它,这样您至少可以设计UI,更好地了解最终产品的外观:
仅供参考,如果你确实可以设计这个,他们建议你为你的设计创建一个单独的框架目标(这样,如果你在处理你的主项目时去IB,那么渲染可设计视图的能力就不是这样了。受到主要项目可能处于稳定,可编辑状态这一事实的影响。
答案 1 :(得分:0)
也许制作一个可以在界面构建器中下拉的自定义视图?此版本具有您可以在IB中设置的属性,用于确定倾斜分数,以便您可以按照自己的方式调整大小:
@IBDesignable class SlantedView: UIView {
@IBInspectable var slant: Double = 0.8
override func prepareForInterfaceBuilder() {
// Called when initialized in IB
setup()
}
override func awakeFromNib() {
// Called when initialized in actual app
setup()
}
func setup() {
layer.backgroundColor = UIColor.yellow.cgColor
recalculateMask()
}
func recalculateMask() {
let shapeLayer = CAShapeLayer()
let maskPath = CGMutablePath()
maskPath.move(to: CGPoint(x: 0, y: 0))
maskPath.addLine(to: CGPoint(x: bounds.width, y: 0))
maskPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
maskPath.addLine(to: CGPoint(x: 0, y: bounds.height * CGFloat(slant)))
shapeLayer.path = maskPath
layer.mask = shapeLayer
}
override func layoutSubviews() {
super.layoutSubviews()
recalculateMask()
}
}