iOS - 自定义 UIView 未显示在设备上

iOS - Custom UIView doesn't show up on device

我有一个自定义 UIView 子class,我想将其添加为 UIViewController 上的子视图。问题是,当我 运行 应用程序时,视图没有显示,即使一切设置正确(在 viewDidLoad 中视图有一个正确的框架,而不是 hidden ) 并显示在 Interface Builder 中 (picture)。在设备上,我只有一个红色屏幕,中间没有三角形。

这是子视图class:

@IBDesignable
class TriangleView: UIView {

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)

        let path = UIBezierPath()
        let width = rect.size.width
        let height = rect.size.height
        let startingPoint = CGPoint(x: center.x, y: center.y - height / 2)

        path.moveToPoint(startingPoint)
        path.addLineToPoint(CGPoint(x: center.x + width / 2, y: center.y - height / 2))
        path.addLineToPoint(CGPoint(x: center.x, y: center.y + height / 2))
        path.addLineToPoint(CGPoint(x: center.x - width / 2, y: center.y - height / 2))
        path.closePath()

        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = rect
        shapeLayer.position = center
        shapeLayer.path = path.CGPath
        shapeLayer.fillColor = UIColor.whiteColor().CGColor

        layer.mask = shapeLayer

        layer.backgroundColor = UIColor.redColor().CGColor
    }
} 

我没有任何其他代码要显示,我只是将视图添加到 ViewController 并将其约束和 class 设置为 TriangleView

你试过了吗,

[self.view bringSubviewToFront:TriangleView]

在将 TriangleView 添加为视图控制器的子视图后放置它。

Swift 3

我致力于简化您所拥有的。我知道这已经过时了,但我相信这是行之有效的方法,它可以实现您想要做的事情:

@IBDesignable
class TriangleView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let width = rect.size.width
        let height = rect.size.height

        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: width, y: 0))
        path.addLine(to: CGPoint(x: width/2, y: height))
        path.close()
        path.stroke()

        let shapeLayer = CAShapeLayer()
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.path = path.cgPath

        layer.addSublayer(shapeLayer)
        layer.backgroundColor = UIColor.red.cgColor
    }
}

一些差异:

  • 三角形我只用了 3 个点而不是 4 个点,然后关闭它。

  • 前2个点在UIView的一角。

  • 我加了layer.addSublayer(shapeLayer)。我相信这就是为什么它在 运行 应用程序时没有出现的原因。

  • 删除了一些我认为不需要的代码,但如果您认为需要,可以将其添加回来。