Make a UIView stick to bottom of the ViewController frame in Swift

19.3k Views Asked by At

I have created a UIView (it's just a blue rectangle) and I want it to stick to the bottom of the frame/view of the screen.

var nextBar = UIView()

nextBar.backgroundColor = UIColor(red: 7/255, green: 152/255, blue: 253/255, alpha: 0.5)
nextBar.frame = CGRect(x: 0, y: 600, width: self.view.frame.width, height: 50)
self.view.addSubview(nextBar)

I'm assuming i need to add something in after the 'y:' part in the CGRect, but i can't seem to make it work or find anywhere that shows me this in swift.

Thanks in advance

3

There are 3 best solutions below

7
On BEST ANSWER

hmmm try this...

override func viewDidLoad() {
  super.viewDidLoad()

  let theHeight = view.frame.size.height //grabs the height of your view

  var nextBar = UIView()

  nextBar.backgroundColor = UIColor(red: 7/255, green: 152/255, blue: 253/255, alpha: 0.5)

  nextBar.frame = CGRect(x: 0, y: theHeight - 50 , width: self.view.frame.width, height: 50)

  self.view.addSubview(nextBar)

}

for the 'y:' in CRect, you're taking the size, in height, of the screen size and you're subtracting how many ever pixels you want. It will appear the same for what ever screen size.

0
On

You can do it programmatically using constraints

fileprivate func setupName(){
        let height = CGFloat(50)

        lblName.text = "Hello world"
        lblName.backgroundColor = .lightGray

        //Step 1
        lblName.translatesAutoresizingMaskIntoConstraints = false

        //Step 2
        self.view.addSubview(lblName)

        //Step 3
        NSLayoutConstraint.activate([

            lblName.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
            lblName.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
            lblName.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor,constant: -height),
            lblName.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
            ])

    }

Please refer link for more details

enter image description here

0
On

Like this:

view.addConstraintsWithFormat(format: "V:[v0(50)]|", views: nextBar)