1

I am trying to add UIView with the bottom border programatically to stack view.But border is not getting added to UIView(). Code to add UIView to stack view:

    func addOtpViews()
    {
        var otpLength=Int(otpLen as String)!
        print("otpLength is\(otpLength)")

        var i=0;
        while(i<=otpLength)
        {
             var view=UIView(frame: .zero)
            addBottomBorderTo(view: view)
            otpStackView.addArrangedSubview(view)
            i=i+1

        }
        otpStackView.translatesAutoresizingMaskIntoConstraints=false

      }

on the above otpStackView is a stack view which I have already added in StoryBoard.

code to add bottom line:

    func addBottomBorderTo(view:UIView) {
        print("bottom is added")
         let layer = CALayer()
         layer.backgroundColor = UIColor.gray.cgColor
         layer.frame = CGRect(x: 0.0, y: view.frame.size.height - 2.0, width: view.frame.size.width, height: 2.0)
         view.layer.addSublayer(layer)
     }

Why bottom line is not added to UIView()?Please help me.Thanks in advance.

Priya Kavi
  • 57
  • 6

1 Answers1

0

have you checked the view frame here

layer.frame = CGRect(x: 0.0, y: view.frame.size.height - 2.0, width: view.frame.size.width, height: 2.0)

view.frame could be (0,0),then you will not see the bottom line.

always be careful when you work with view frame.

My suggestions: 1.Adding sub view instead of adding sub layer,then use snapkit to layout. 2.Build a seperate view class called bottomedView,then add sub view there with snapkit. 3.Build a seperate view class called bottomedView,and draw your bottom line in onDraw.

Always be aware view frame may not be determined when view is missing unexpectedly.

Charlie Cai
  • 281
  • 1
  • 6