Home > Mobile >  UIView is not showing up on my root UIViewController
UIView is not showing up on my root UIViewController

Time:06-08

I have created a UIView and tried adding it with view.addSubview but its not showing up for some reason.

This is my UIViewController:

private let titleLabel: UILabel = { // Create a UILabel programatically
    //...
}()

private let emailContainerView: UIView = {
    let view = UIView()
    
    view.backgroundColor = .blue
    
    return view
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.init(red: 25/255, green: 25/255, blue: 25/255, alpha: 1)
    
    addSubviews()
    layout()
    
}

//A function for adding new subviews
private func addSubviews() {
    view.addSubview(emailContainerView)
    view.addSubview(titleLabel)
}

//A function for autolayout
private func layout() {
    titleLabel.anchor(top: view.safeAreaLayoutGuide.topAnchor)
    titleLabel.centerX(inView: view)
    
    emailContainerView.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, right: view.rightAnchor, paddingTop: 40, paddingLeft: 16, paddingRight: 16, height: 50)
}

And i also created a function(anchor) which handles my constraints.

func anchor(top: NSLayoutYAxisAnchor? = nil,
            left: NSLayoutXAxisAnchor? = nil,
            bottom: NSLayoutYAxisAnchor? = nil,
            right: NSLayoutXAxisAnchor? = nil,
            paddingTop: CGFloat = 0,
            //padding left,right,bottom is the same
            width: CGFloat? = nil,
            height: CGFloat? = nil) {
    
    translatesAutoresizingMaskIntoConstraints = false
    
    if let top = top {
        topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
    }
    
    if let left = left {
        leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
    }
    
    if let bottom = bottom {
        bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
    }
    
    if let right = right {
        rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
    }
    
    if let height = height {
        widthAnchor.constraint(equalToConstant: height).isActive = true
    }
    //Width...
    
}

And this is what i see after running my project on Iphone 13 mini simulator

:

CodePudding user response:

At the last in function anchor you are settinh width but you also giving left and right anchor this will cause visual issue .

I think you wanted set it

   if let height = height {
    heightAnchor.constraint(equalToConstant: height).isActive = true // change width to height
    }

if let bottom = bottom { .. } is not gonna work because you are not passing any value from anchor function . so your view has top,left,right and now (with above code) height . Everything must work

  • Related