Search code examples
iosswiftxcodeuibezierpathcashapelayer

How can i see the drawing in storyboard?


I drawed triangle but I can't see on storyboard. How can I see on storyboard this drawing ?

enter image description here View Controller Code:

class ViewController: UIViewController {

    @IBOutlet weak var fooView: UIView!

    var polygonShape = CAShapeLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let polygonPath = UIBezierPath()
        polygonPath.move(to: CGPoint(x: 50, y: -1))
        polygonPath.addLine(to: CGPoint(x: 93.3, y: 74))
        polygonPath.addLine(to: CGPoint(x: 6.7, y: 74))
        polygonPath.close()

        polygonShape.frame = fooView.bounds
        polygonShape.path = polygonPath.cgPath

        fooView.layer.mask = polygonShape

    }
}

Solution

  • Change your class to this:

    @IBDesignable
    class FirstImageView: UIView {
    
        var polygonShape: CAShapeLayer!
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            commonInit()
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            commonInit()
        }
    
        func commonInit() -> Void {
    
            if polygonShape == nil {
                polygonShape = CAShapeLayer()
                layer.mask = polygonShape
            }
    
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            let polygonPath = UIBezierPath()
            polygonPath.move(to: CGPoint(x: 0.0, y: bounds.size.height))
            polygonPath.addLine(to: CGPoint(x: bounds.width * 0.5, y: 0.0))
            polygonPath.addLine(to: CGPoint(x: bounds.size.width, y: bounds.size.height))
            polygonPath.close()
    
            polygonShape.path = polygonPath.cgPath
        }
    
    }
    

    You can remove everything from your ViewController class. You don't even need the class at all at this point.

    Select the view on your Storyboard, and at the top of the Identity Inspector pane change the Custom Class from the default UIView to FirstImageView.

    Under the top Editor menu, either select Refresh All Views or make sure Automatically Refresh Views is checked.

    Result:

    enter image description here