Перерисовка TabBar при переходе на другие вкладки

Разрабатываю приложение на UIKit. В нем использую CustomTabBar. При переключении вкладок TabBar необходимо изменить его отрисовку. Помогите реализовать пожалуйста. Как понимаю, функция draw() в данном случае единожды отрисовывает TabBar.

введите сюда описание изображения введите сюда описание изображения

Код отрисовки:

private func shapePath() -> CGPath {
    
    let path = UIBezierPath()
    let height: CGFloat = 35.0
    let centerWidth = self.frame.width / 2
    
    path.move(to: CGPoint(x: 15, y: 0)) // start top left
    path.addLine(to: CGPoint(x: (centerWidth - height * 2), y: 0)) // the beginning of the trough

    if selectedItem?.title == "Accounts" {
    // first curve down
    path.addCurve(to: CGPoint(x: centerWidth, y: height),
                  controlPoint1: CGPoint(x: (centerWidth - 22), y: 0), controlPoint2: CGPoint(x: centerWidth - 37, y: height))
    // second curve up
    path.addCurve(to: CGPoint(x: (centerWidth + height * 2), y: 0),
                  controlPoint1: CGPoint(x: centerWidth + 37, y: height), controlPoint2: CGPoint(x: (centerWidth + 22), y: 0))
    }

    // complete the rect
    path.addLine(to: CGPoint(x: self.frame.width - 15, y: 0))
    path.addArc(withCenter: CGPoint(x: self.frame.width - 15, y: 15),
                radius: 15,
                startAngle:  3 * .pi / 2,
                endAngle:  0,
                clockwise: true)
    path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
    path.addLine(to: CGPoint(x: 0, y: self.frame.height))
    path.addLine(to: CGPoint(x: 0, y: 15))
    path.addArc(withCenter: CGPoint(x: 15, y: 15),
                radius: 15,
                startAngle: .pi,
                endAngle:  3 * .pi / 2,
                clockwise: true)
    path.close()
    return path.cgPath
}

private func drawTabBar() {
    
    let shapeLayer = CAShapeLayer()
    
    shapeLayer.path = shapePath()
    shapeLayer.strokeColor = UIColor.lightGray.cgColor
    shapeLayer.fillColor = UIColor(red: 155/255, green: 160/255, blue: 163/255, alpha: 1).cgColor
    shapeLayer.lineWidth = 3.0
    
    if let oldShapeLayer = self.shapeLayer {
        self.layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
    } else {
        self.layer.insertSublayer(shapeLayer, at: 0)
    }
    
    self.shapeLayer = shapeLayer
}

override func draw(_ rect: CGRect) {
    drawTabBar()
}

Ответы (1 шт):

Автор решения: schmidt9

Для принудительной перерисовки вашего кастомного вью используйте вызов setNeedsDisplay(). Перед этим вам разумеется нужно каким-то образом сообщить вью, как оно должно рисовать путь - с вырезом или прямо.

Например реализовать внутри вью метод наподобие такого и вызывать его из вью контроллера

public func update(usingCurvedShape: Bool) {
     if usingCurvedShape {
         // ...
     } else {
        // ...
     }

     setNeedsDisplay()
}
→ Ссылка