How to change the border color below the navigation bar?

前端 未结 6 1884
甜味超标
甜味超标 2020-12-28 19:40

Can anyone advise me on how the border below the navigation bar can be changed?

\"enter

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 20:12

    I found a couple of issues with the previous answers:

    • if you add a subview: Upon rotation of the device, the border will not have the correct frame anymore
    • if you set the shadowImage to nil, then you cannot customize the shadow of the navigationBar.

    One way of solving this would be to use autolayout:

    extension UINavigationBar {
    
      func setBottomBorderColor(color: UIColor, height: CGFloat) -> UIView {
        let bottomBorderView = UIView(frame: CGRectZero)
        bottomBorderView.translatesAutoresizingMaskIntoConstraints = false
        bottomBorderView.backgroundColor = color
    
        self.addSubview(bottomBorderView)
    
        let views = ["border": bottomBorderView]
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[border]|", options: [], metrics: nil, views: views))
        self.addConstraint(NSLayoutConstraint(item: bottomBorderView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: height))
        self.addConstraint(NSLayoutConstraint(item: bottomBorderView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: height))
    
        return bottomBorderView
      }
    }
    

    The reason why I return the border is that during rotation you do see it in the middle of the navigation bar, so I hide it during the rotation.

提交回复
热议问题