Henny Lee
Henny Lee

Reputation: 3052

CAShapelayer not showing

I've been trying to add a layer to my views and buttons but somehow the layer isn't appearing at all. What am I missing?

class ViewController: UIViewController {

    var button1: CustomButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        button1 = CustomButton(frame: CGRectZero)

        let views1 = ["button1": button1]

        button1.backgroundColor = .clearColor()
        view.addSubview(button1)

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[button1(50)]", options: [], metrics: nil, views: views1))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[button1(50)]-50-|", options: [], metrics: nil, views: views1))
    }
}

class CustomButton: UIButton {

    let shape = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)

        translatesAutoresizingMaskIntoConstraints = false

        shape.fillColor = UIColor.redColor().CGColor
        shape.strokeColor = UIColor.blackColor().CGColor
        shape.lineWidth = 0.5

        shape.bounds = CGRect(x: 0, y: 0, width: 50, height: 50)

        layer.insertSublayer(shape, atIndex: 0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let padding: CGFloat = 10

        let x = frame.origin.x - padding
        let y = frame.origin.y - padding
        let widths = bounds.width  + 2 * padding
        let height = bounds.height + 2 * padding

        let rect = CGRect(x: x, y: y, width: widths, height: height)

        shape.frame = rect
        shape.path = UIBezierPath(rect: rect).CGPath
    }
}

The button is added to the view without problems but nothing of the layer seems visible (been trying to change colors when tapped etc as well, setting the position or just edit the layer itself without adding a new one).

Upvotes: 0

Views: 437

Answers (1)

Aruna Mudnoor
Aruna Mudnoor

Reputation: 4825

You missed '|' in your constraint string. Please update as,

    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[button1(50)]|", options: [], metrics: nil, views: views1))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button1(50)]-50-|", options: [], metrics: nil, views: views1))

Upvotes: 0

Related Questions