Swift remove a button BottomBorder

So I have buttons that add a nice border when clicked, I cannot find a way to remove the borders, because I only want one border at a time. I have tried setting the width to 0 etc.

@IBAction func podsButtonClicked(_ sender: UIButton) {
    podsButton.addBottomBorderWithColor(color: greenColor(), width: 3)
}

@IBAction func subscribedButtonClicked(_ sender: UIButton) {
    subscribedButton.addBottomBorderWithColor(color: greenColor(), width: 3)
}

@IBAction func subscribersButtonClicked(_ sender: UIButton) {
    subscribersButton.addBottomBorderWithColor(color: greenColor(), width: 3)
}

In each button I would like to remove the border from the others, per se.

1 answer

  • answered 2017-11-12 20:16 Andrés Pizá

    addBottomBorderWithColor is, I'm guessing, a method you have added as an extension of UIButton in your project. Depending on how it adds the bottom border you'll have to do one of the following:

    If you are adding the bottom border of the button as a subview, you'll need to create a method that does the following:

    func removeBottomBorder() {
        bottomBorder.removeFromSuperview()
    }
    

    If, instead, you are adding the bottom border as a sublayer, you'll need to do this:

    func removeBottomBorder() {
        bottomBorder.removeFromSuperlayer()
    }
    

    I recommend you create a custom button subclass that manages the bottom border, it will be more or less similar to this:

    class BottomBorderButton: UIButton {
        var bottomBorder: UIView? // If you are using a CALayer, use that instead
    
        func addBottomBorderWithColor(color: UIColor, width: Int) {
            let bottomBorder = UIView() // If you are using a CALayer, use that instead
            // Use whatever you have already implementeds here
            // ...
            self.bottomBorder = bottomBorder
        }
    
        func removeBottomBorder() {
            self.bottomBorder?.removeFromSuperview()
            // If you use a CALayer, use the following instead
            // self.bottomBorder?.removeFromSuperlayer()
        }
    }
    

    On your project then use BottomBorderButton instead of UIButton where needed.