Raghav N
Raghav N

Reputation: 39

Overlap UIButton on two or more views on swift

I want this button to overlap on two or more views

I am trying to overlap the button on two or more views. So when I add this on the first view it is not showing on the second view so I want one button must shown on two views.

Upvotes: 0

Views: 1141

Answers (3)

dounia belannab
dounia belannab

Reputation: 1

You need either to

  • add the button as the very last so that it can be the top one on the subviews stack
  • or to apply the superview.bringSubviewToFront(button)

Upvotes: 0

Jagan
Jagan

Reputation: 1

Did you try this? You need to add the button to the container subview and add

this line container.bringSubviewToFront(button)

https://www.hackingwithswift.com/example-code/uikit/how-to-bring-a-subview-to-the-front-of-a-uiview

Upvotes: 0

Motivation gym5
Motivation gym5

Reputation: 291

You can make two views and embed second view to first and then button to second View and can play with its Y axis

class overlapViewcontroller:UIViewController {
    
    private let firstView:UIView = {
        let view = UIView(frame: CGRect(x: 10,
                                        y: 100,
                                        width: 350,
                                        height: 50))
        view.backgroundColor = .green
        return view
    }()
    
    private let secondView:UIView = {
        let view = UIView(frame: CGRect(x: 10,
                                        y: 10,
                                        width: 330,
                                        height: 30))
        view.backgroundColor = .purple
        return view
    }()
    
    private let button:UIButton = {
        let button = UIButton(frame: CGRect(x: 10,
                                            y: -5,
                                            width: 310,
                                            height: 20))
        button.setTitle("Button", for: .normal)
        button.backgroundColor = .systemOrange
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
        view.addSubview(firstView)
        firstView.addSubview(secondView)
        secondView.addSubview(button)
    }
}

First View:Green,Second View:purple

Upvotes: 1

Related Questions