Fahadsk
Fahadsk

Reputation: 1109

Adding a sub layer or UIView as subview to the top using z-order of UIButton still goes behind the view or look transparent

I have a UIButton and i want to add a circle badge on top of it, here is how it looks.

public func addCircleBadge(_ width: CGFloat, color: UIColor) {
        let bounds = self.mybtn.bounds
        let layer = CAShapeLayer()
        let radius = width / 2
        layer.path = UIBezierPath(roundedRect: CGRect(x: bounds.width - (radius + 2.0), y: bounds.minY - (radius-2.0), width: width, height: width), cornerRadius: radius).cgPath
        layer.fillColor = color.cgColor
        layer.zPosition = 999
        layer.name = "circleBadge"
        self.mybtn.layer.addSublayer(layer)
    }

and in viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    mybtn.layer.borderColor = UIColor.blue.cgColor
    mybtn.layer.cornerRadius = 3.0
    mybtn.layer.borderWidth = 2.0
    mybtn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    addCircleBadge(20, color: UIColor.red.withAlphaComponent(1.0))
}

but this layer is looking transparent, so the button area is visible, i want to have an opaque layer on top of button. can it be done through layer or do i need to add a different view and place both button and this separate UIView in a common view

button with ca layer

Upvotes: 2

Views: 3846

Answers (1)

Roman Tsymbaliuk
Roman Tsymbaliuk

Reputation: 311

As I understand you set borderWidth and borderColor for button.layer. This button.layer hosts all other sublayer that you add to them that's why your border is always on the top.

So you can use additional view for drawing the circle or... Just remove setting borderWidth and borderColor for button.layer and add another sublayer that will cover your border.

For example:

    func addBorder(borderWidth: CGFloat = 1.0, borderColor: UIColor = UIColor.blue) {
        let layer = CALayer()
        let frame = self.mybtn.frame
        layer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
        layer.borderColor = borderColor.cgColor
        layer.borderWidth = borderWidth
        self.mybtn.layer.addSublayer(layer)
    }

and in ViewDidLoad:

    override func viewDidLoad() {
        super.viewDidLoad()
        addBorder()
        addCircleBadge(20, color: UIColor.red)
    }

Also one update for addCircleBadge

    public func addCircleBadge(_ width: CGFloat, color: UIColor) {
        ...

        self.mybtn.layer.insertSublayer(layer, at: 0)
    }

Upvotes: 2

Related Questions