How to order views' layers on top of each others in Swift

How to bring the red view to be on top of the border of the text field?

I added the redView as a subView of the textField and used AutoLayout to constraint it to be as it appears in the image, but the problem here now is I want to bring the red view to be on top of the border I tried to use this method bringSubviewToFront(floatingPlaceholderContainer) but it didn't work, also tried to use the layer.zPosition = .greatestFiniteMagnitude and it also didn't work

Edit- the code I used and didn't work as I expected

override func layoutSubviews() {
        super.layoutSubviews()
        self.redlayer.backgroundColor = UIColor.red.cgColor
        self.redlayer.frame = CGRect(x: 10, y: -10, width: 100, height: 30)
        self.layer.addSublayer(self.redlayer)
        self.redlayer.zPosition = 10
    }

and this is the result enter image description here

1 answer

  • answered 2021-09-11 18:31 matt

    You need to configure the timing of when you're adding this layer. This approach works fine for me:

    class MyTextField : UITextField {
        let redlayer = CALayer()
        override func layoutSubviews() {
            super.layoutSubviews()
            self.redlayer.backgroundColor = UIColor.red.cgColor
            self.redlayer.frame = CGRect(x: 10, y: -10, width: 100, height: 30)
            self.layer.addSublayer(self.redlayer)
            self.redlayer.zPosition = 10
        }
    }
    

    enter image description here

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum