Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a button has this image


I want to check if myButton has a named image.

I try this but it doesn't work

if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }

and this too doesn't work

if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }
like image 207
Rombond Avatar asked Dec 06 '22 14:12

Rombond


1 Answers

Here is what I came up with in Swift 3.0.

if let myButtonImage = myButton.image(for: .normal),
    let buttonAppuyerImage = UIImage(named: "ButtonAppuyer.png"),
    UIImagePNGRepresentation(myButtonImage) == UIImagePNGRepresentation(buttonAppuyerImage)
{
    print("YES")
} else {
    print("NO")
}

This could be cleaned up a lot.

extension UIButton {
    func hasImage(named imageName: String, for state: UIControlState) -> Bool {
        guard let buttonImage = image(for: state), let namedImage = UIImage(named: imageName) else {
            return false
        }

        return UIImagePNGRepresentation(buttonImage) == UIImagePNGRepresentation(namedImage)
    }
}

Then use it

if myButton.hasImage(named: "ButtonAppuyer.png", for: .normal) {
    print("YES")
} else {
    print("NO")
}
like image 144
Jeffery Thomas Avatar answered Dec 23 '22 07:12

Jeffery Thomas