Jeppe Christensen Jeppe Christensen - 1 month ago 17
Swift Question

how to change bordercolor when Button.isHighlighted

I wonder how I get my border around my

UIButton
to change opacity together with the text inside it, when it is either clicked or highlighted.

My logic tells me, that it should be something like this.. but it doesn't seem to work:

//BTN STYLING

btnstd.layer.cornerRadius = 5
btnstd.layer.borderWidth = 1.5
btnstd.layer.borderColor = UIColor.white.cgColor

//Change bordercolor when highlighted
if(btnstd.isHighlighted) {
btnstd.layer.borderColor = UIColor(white:1,alpha:0.3).cgColor
}


This is by the way put inside my
ViewDidLoad()
function

dfd dfd
Answer

I tested this out, hope it works for what you need! Or at least points you in a direction. The actions you are looking for (I think) are .touchDown and anything .touchUp.

override func viewDidLoad() {
    super.viewDidLoad()
    theButton.setTitle("Normal", for: .normal)
    theButton.setTitle("Highlighted", for: .highlighted)
    theButton.layer.borderColor = UIColor.red.cgColor
    theButton.layer.borderWidth = 1
    theButton.addTarget(self, action: #selector(startHighlight), for: .touchDown)
    theButton.addTarget(self, action: #selector(stopHighlight), for: .touchUpInside)
    theButton.addTarget(self, action: #selector(stopHighlight), for: .touchUpOutside)
}
func startHighlight(sender: UIButton) {
    theButton.layer.borderColor = UIColor.green.cgColor
    theButton.layer.borderWidth = 1
}
func stopHighlight(sender: UIButton) {
    theButton.layer.borderColor = UIColor.red.cgColor
    theButton.layer.borderWidth = 1
}