UINavigationBar底部边框消失

时间:2018-05-09 07:05:11

标签: ios swift override uinavigationbar draw

我是UINavigationBar的子类,在界面构建器中,我使用Identity Inspector将其设置为NavigationBar的{​​{1}}的类。问题是,当我覆盖draw方法时,UINavigationController的下边框消失了。这是我的代码:

navigationBar

通过覆盖这种方法发生的事情太荒谬了。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这里有两个主要选项:

  1. 自己画一条线:

    override func draw(_ rect: CGRect) {
        super.draw(rect)
    
        // your other code here.
    
        if rect.maxY == self.bounds.maxY {
            if let context = UIGraphicsGetCurrentContext() {
                context.setStrokeColor(UIColor.red.cgColor)
                context.setLineWidth(1)
                context.move(to: CGPoint(x: 0, y: bounds.height))
                context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
                context.strokePath()
            }
        }
    }
    
  2. 在Interface Builder中向栏添加子视图1px高度。

  3. P.S。不要在drawRect()方法中执行布局代码。完全出于这个目的存在一个特定的重点:

    open func layoutSubviews() // override point. called by layoutIfNeeded automatically. As of iOS 6.0, when constraints-based layout is used the base implementation applies the constraints-based layout, otherwise it does nothing.
    
    
        /* -layoutMargins returns a set of insets from the edge of the view's bounds that denote a default spacing for laying out content.
         If preservesSuperviewLayoutMargins is YES, margins cascade down the view tree, adjusting for geometry offsets, so that setting
         the left value of layoutMargins on a superview will affect the left value of layoutMargins for subviews positioned close to the
         left edge of their superview's bounds
           If your view subclass uses layoutMargins in its layout or drawing, override -layoutMarginsDidChange in order to refresh your 
         view if the margins change.
           On iOS 11.0 and later, please support both user interface layout directions by setting the directionalLayoutMargins property
         instead of the layoutMargins property. After setting the directionalLayoutMargins property, the values in the left and right
         fields of the layoutMargins property will depend on the user interface layout direction.
         */