'keep the original color of the UIButton's icon when it's tapped in Swift

I'm working on making a custom UIButton in Swift and have a question for initializing the UIButton with type custom.

This is the image of the current custom button in my project, and when the user taps a button, the image icon, whose the original color is .whilte, grays out. However, I want to keed the image color to white even when the user taps the button and the button state changes. I think I should initialize the button with type custom, but I get the message like, Must call a designated initializer of the superclass 'UIButton', when I try initializing with init(type: UIButton.ButtonType), so could someone point me to the right direction, please?

enter image description here

Here is the code, for the custom button class.

import UIKit

class MyCapsuleButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        configure()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    init(backgroundColor: UIColor, title: String, textColor: UIColor) {
        super.init(frame: .zero)
        // super.init(type: .custom) -> tried to initialize with type, but didn't work
        self.backgroundColor = backgroundColor
        self.setTitle(title, for: .normal)
        self.setTitleColor(textColor, for: .normal)
        configure()
    }

    func configure() {
        translatesAutoresizingMaskIntoConstraints = false
        titleLabel?.font = UIFont.customNormal()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.frame.height / 2
    }
}

and I call as

lazy var deletionButton: MyCapsuleButton = {
    let button = MyCapsuleButton(backgroundColor: .Red(), title: "DELETE", textColor: .white)
    button.setImage(Images.delete, for: .normal)
    return button
}()

I read the documentation and it says You specify the type of a button at creation time using the init(type:) method, I thought I need to call super.init(type: .custom) in the custom initializer, but I get a "Must call..." error on the storyboard. Also, I dont't use a storyboard in this project, and I want to know how can I call type custom with some custom init parameters, like backgroundColor, title, textColor.


Add this part later...

So, it seems when I make a subclass of UIButton, the type is gonna be custom by default. (I printed out the type and figured out.)

So is setting button.setImage(Images.delete, for: .normal) makes the trash icon gray?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source