0

I have a custom UIView subclass, that I want to add as a subview on my UIViewController. The problem is, that the view doesn't show up, when I run the app, even though everything is set correctly (in viewDidLoad the view has a correct frame and is not hidden) and it shows up in Interface Builder (picture). On the device I only get a red screen, no triangle in the middle.

Here's the view subclass:

@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
    }
} 

I don't have any other code to show, I just add the view to the ViewController and set its constraints and class to TriangleView.

Mark Moeykens
  • 15,915
  • 6
  • 63
  • 62
smeshko
  • 1,184
  • 13
  • 27

2 Answers2

4

Swift 3

I worked on simplifying what you have. I know this is old but here is something that works which I believe achieves what you were trying to do:

@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
    }
}

A few differences:

  • I only use 3 points instead of 4 for the triangle then close it.

  • The first 2 points are in the corner of the UIView.

  • I added layer.addSublayer(shapeLayer). I believe this is why it wasn't showing up when running the app.

  • Removed some code that I don't think was needed but you can add it back if you believe so.

Simulator

Mark Moeykens
  • 15,915
  • 6
  • 63
  • 62
0

Have you tried,

[self.view bringSubviewToFront:TriangleView]

Put this after adding your TriangleView as a subview of your view controller.

Daniel Que
  • 1,734
  • 4
  • 20
  • 31
Avinash Sharma
  • 665
  • 1
  • 7
  • 23