Zachary Smouse
Zachary Smouse

Reputation: 143

UIButton has Blue Tint When Tapped

I'm trying to make an UIButton turn my purple hex color with white text when users tap to choose Current Location, then make it switch back to a white background with purple text. However, I'm running into a problem where when I tap for the first time, my text has a blue tint behind the text. I have tried to set the tint to clear to try and fix the issue, but it makes the text disappear. What can I do to get this working? Thank you!

My Issue

enter image description here

ServiceDetailController

lazy var currentLocationButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Current Location", for: .normal)
    button.setTitleColor(UIColor.darkPurpleTint, for: .normal)
    button.backgroundColor = .white
    button.layer.borderWidth = 2
    button.layer.borderColor = UIColor.darkPurpleTint.cgColor
    button.setDimensions(height: 30, width: 30)
    button.layer.cornerRadius = 30 / 2
    button.addTarget(self, action: #selector(currentLocationTapped(_:)), for: .touchUpInside)
    return button
}()

@objc func currentLocationTapped(_ sender: UIButton) {
        
    if sender.isSelected {
       sender.backgroundColor = .darkPurpleTint
       sender.setTitleColor(.white, for: .normal)
       sender.isSelected.toggle()
    } else {
       sender.backgroundColor = .white
       sender.setTitleColor(.darkPurpleTint, for: .normal)
       sender.isSelected.toggle()
    }
        
}

Upvotes: 0

Views: 551

Answers (1)

DonMag
DonMag

Reputation: 77540

You can save yourself some code by taking advantage of the .selected state of the button...

lazy var currentLocationButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Current Location", for: [])
    
    // title color when normal
    button.setTitleColor(UIColor.darkPurpleTint, for: .normal)
    
    // title color when selected
    button.setTitleColor(.white, for: .selected)
    
    // tint color clear removes the "blue box" when selected
    button.tintColor = .clear
    
    button.backgroundColor = .white
    button.layer.borderWidth = 2

    button.layer.borderColor = UIColor.darkPurpleTint.cgColor
    
    // don't know what you're doing here...
    //button.setDimensions(height: 30, width: 30)
    
    button.layer.cornerRadius = 30 / 2
    button.addTarget(self, action: #selector(currentLocationTapped(_:)), for: .touchUpInside)
    return button
}()

@objc func currentLocationTapped(_ sender: UIButton) {

    sender.isSelected.toggle()

    // change the background color
    sender.backgroundColor = sender.isSelected ? .darkPurpleTint : .white
    
}

Upvotes: 1

Related Questions