Neulio
Neulio

Reputation: 332

How can I center a button on view programmatically

I am trying to center a Button onto the bottom of a view but it never appears. The only time it appears is when I uncomment takePhotoButton.frame. What is the proper way to do this?

 import UIKit
 import AVFoundation


class InputViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

       let photoPreviewImageView = UIImageView()
        photoPreviewImageView.frame = view.bounds
        photoPreviewImageView.backgroundColor = UIColor.green
        view.addSubview(photoPreviewImageView)

        let imageOfPhotoButton = UIImage(named: "smallcircle.circle.fill") as UIImage?
        let takePhotoButton = UIButton(type: .custom) as UIButton
        takePhotoButton.setImage(imageOfPhotoButton, for: .normal)
        //takePhotoButton.frame = CGRect(x: 10, y: 10, width: 60, height: 60) // It will appear with this code however i took it away because im trying to center it at the bottom of the screen
        takePhotoButton.center = view.center
        photoPreviewImageView.addSubview(takePhotoButton)

    }




}

Upvotes: 0

Views: 378

Answers (2)

ff10
ff10

Reputation: 3147

Use constraint anchors. After you add the takePhotoButton set them the following way:

takePhotoButton.bottomAnchor.constraint(equalTo: photoPreviewImageView.bottomAnchor).isActive = true
takePhotoButton.centerXAnchor.constraint(equalTo: photoPreviewImageView.centerXAnchor).isActive = true

This will set make your button have the same bottom and center as it's container.

Upvotes: 1

cristian_064
cristian_064

Reputation: 606

Good day, you have to add constraint.

import UIKit

class ViewController: UIViewController {

    var loginButton : UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Login", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .red
        button.tintColor = .white
        return button
    }()




    override func viewDidLoad() {
        super.viewDidLoad()


        constraintsInit()
    }


    func constraintsInit(){
        view.addSubview(loginButton)
        NSLayoutConstraint.activate([
            loginButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            loginButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            loginButton.heightAnchor.constraint(equalToConstant: 30),
            loginButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor,constant: 30),
            loginButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor,constant: -30),
        ])
    }

}

on youtube you can find several people that explain how create the views, using only code.

Upvotes: 0

Related Questions