I'm trying to check the image name in the UIButton like this:
#IBAction func buttonTapped(_ sender: Any) {
if xcodeButton.currentImage == UIImage(named: "xcode") {
print("xcode image")
}
}
But I have a break point in the if statement and this is the output:
po xcodeButton.currentImage
▿ Optional<UIImage>
- some : <UIImage:0x6000011a93b0 named(main: xcode) {500, 500}>
but if I compare it
po xcodeButton.currentImage == UIImage(named: "xcode")
false
Any of you knows why the comparison is returning false? or how can compare the name of the image in UIButton?
I'll really appreciate your help.
You should use isEqual(_:) From Docs scroll to Comparing Images section
let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage")
if image1 != nil && image1!.isEqual(image2) {
// Correct. This technique compares the image data correctly.
}
if image1 == image2 {
// Incorrect! Direct object comparisons may not work.
}
None of these solutions were working for me. So I used pngData to compare images:
let image1Data = UIImage(named: "MyImage")?.pngData()
let image2Data = UIImage(named: "MyImage")?.pngData()
if image1Data == image2Data {
// It compares data correctly
}
Related
I am attempting to execute code if an image exist.
The issue is I am unable to capture the state of empty image call.
The result is I get an empty image, but would rather put a placeholder image if possible.
func procImage(inName: String) {
switch (inName) {
case inName:
imageName = inName.lowercased()
default:
imageName = "blank"
}
}
This check is easy but you need to be sure that default image always exists.
func getSafeImage(named: String) -> Image {
let uiImage = (UIImage(named: named) ?? UIImage(named: "Default.png"))!
return Image(uiImage: uiImage)
}
Try this code:
func procImage(inName: String) -> UIImage {
if let confirmedImage = UIImage(named: inName) {
return confirmedImage
} else {
return UIImage(named: "Default_Image.png")!
}
}
Thanks all for contributing.
The solutions on offer did not quite work in my case except for Moreno's solution, but offered a path to my solution.
I did not need to store the result of the check, but just validate the existence of the file.
So this is what I came up with which worked.
This may not be the optimal solution, so improved code will be welcomed.
func procImage(inName: String) {
let imageConvertToLowercase = inName.lowercased()
if getMember.firstName.lowercased() == imageConvertToLowercase {
if (UIImage(named: imageConvertToLowercase) != nil) {
imageName = imageConvertToLowercase
} else {
imageName = "blank"
}
}
}
I have 2 UIImageViews connected to an array of images
I'm trying compare both once they are displayed but doesn't seems to work.
I tried using imageArray[Image Literal] and also imageArray[image1.png, image2.png, image3.png, image4.png, image5.png]
I'm not sure what im doing wrong.
im not looking for the code although it may help but what im looking is for a someone to guide me to the right direction
#IBOutlet weak var 1ImageView: UIImageView!
#IBOutlet weak var 2ImageView: UIImageView!
let imageArray = [image1.png, image2.png, image3.png, image4.png, image5.png]
func any() {
if (1ImageView != nil) && (2ImageView != nil) && isEqual(image1.png) {
print("match!")
} else if ...// more if statements
…last if statement} else {
print(“no match!”)
}
#IBAction func buttonPressed(_ sender: IUButton) {
any()
}
If this is not possible is there a way to assign an identifier to each of the images inside the array..
sorry for the extra question.
there is one answer on comparing 2 images using NSData but Im not sure how to implement it to an array.
thanks and sorry but the newbie question.
image.isEqual(image) seems to be unreliable, despite what documentation says. If you don't need to make a pixel perfect comparison, converting image to a data and comparing those would be sufficient.
let image1 = UIImage(named: "image1.png")
let image2 = UIImage(named: "image2.png")
let imageData1 = image1?.pngData()
let imageData2 = image2?.pngData()
if imageData1 == imageData2 {
print("images are the same")
} else {
print("images are different")
}
Looking for a specific image inside an array can build on that:
// array of images referencing image files within an Xcode project
// it's not the best idea to force unwrap those, but for the sake of simplicity
let imageArray = [UIImage(named: "image1.png")!,
UIImage(named: "image2.png")!,
UIImage(named: "image3.png")!,
UIImage(named: "image4.png")!,
UIImage(named: "image5.png")!]
func anySimilarImages() {
// find first image which is the same as 1ImageView's
let 1ImageViewImage: UIImage? = imageArray.first { (image) -> Bool in
return image.pngData() == 1ImageView.image?.pngData()
}
// find first image which is the same as 2ImageView's
let 1ImageViewImage: UIImage? = imageArray.first { (image) -> Bool in
return image.pngData() == 2ImageView.image?.pngData()
}
if 1ImageViewImage != nil && 2ImageViewImage != nil {
print("both images were found")
}
else if 1ImageViewImage != nil {
print("first image was found")
}
else if 2ImageViewImage != nil {
print("second image was found")
}
else {
print("no image was found")
}
}
I am working on a image quiz. I have a button that will display either the correct image or the wrong image if there is no correct image. The unique question number comes from an array.
if (questionlist[1]correct = [UIImage imageNamed:#"questionlist[1]correct.png"]) {
Answer4.setImage(UIImage(named: "\(questionlist[1])correct.png"), forState: UIControlState.Normal)
} else {
Answer4.setImage(UIImage(named: "\(questionlist[1])fourthwrong.png"), forState: UIControlState.Normal)
}
Okay so if I'm understanding your questionList array is simply an array of numbers? So questionList = [1,2,3,etc]? In that case, you may want to try something like:
let imageName = "\(questionList[1])wrong.png" //for instance 2wrong.png
if (UIImage(named: imageName) == nil) { // no wrong image exists
imageView.image = UIImage(named: "\(questionList[1])correct.png")
} else {
imageView.image = UIImage(named: "\(questionList[1])wrong.png")
}
Of course this is assuming a correct image exists. It's unclear what you're after, some more information/more code would help.
I have set a placeholder image for my image views. The user can change these to a photo from their library. Once they have done this, they can then upload these images to a database. The user can upload a single image or many, either way, they are uploaded as an [UIImage]. However, I do not want the placeholder images to be uploaded.
I have managed to achieve this, but in a very ungraceful manner. I have done this by firstly subclassing UIImageView, adding a property called isSet and setting all my image views to this class:
class ItemImageViewClass: UIImageView {
//keeps track of whether the image has changed from the placeholder image.
var isSet = Bool()
}
and then when the image has been set after the user has selected an image, the isSet property is set to true.
To check if the image in the image view has been changed from the placeholder image (i.e. isSet == true) I used the following code:
var imageArray: [UIImage]? = nil
if imageViewOne.isSet {
guard let mainImage = imageViewOne.image else {return}
if (imageArray?.append(mainImage)) == nil {
imageArray = [mainImage]
}
}
if imageViewTwo.isSet {
guard let imageTwo = imageViewTwo.image else {return}
if (imageArray?.append(imageTwo)) == nil {
imageArray = [imageTwo]
}
}
guard imageArray != nil else {
print("imageArray is nil")
alertMessage("Hey!", message: "Please add some images!")
return
}
When at least one image has been selected, the array will be saved to the database.
This seems like a very messy way to do it; subclassing UIImageView and having to check that each image has changed using a series of if statements. Is there a more elegant way to achieve this? Thanks
There is a solution by extending UIImageView to avoid subclassing. And, using filter and flatMap to by pass the if-statements. This requires that you use the same reference to the placeholder image for each UIImageView.
// In this example, the placeholder image is global but it doesn't have to be.
let placeHolderImage = UIImage()
extension UIImageView {
// Check to see if the image is the same as our placeholder
func isPlaceholderImage(_ placeHolderImage: UIImage = placeHolderImage) -> Bool {
return image == placeHolderImage
}
}
Usage:
let imageViewOne = UIImageView(image: placeHolderImage)
imageViewOne.isPlaceholderImage() // true
let imageViewTwo = UIImageView()
imageViewTwo.isPlaceholderImage() // false
let imageViewThree = UIImageView()
imageViewThree.image = UIImage(named: "my-image")
imageViewThree.isPlaceholderImage() // false
Filter and map for images that are not placeholders or nil:
let imageArray = [imageViewOne, imageViewTwo, imageViewThree].filter
{ !$0.isPlaceholderImage() }.flatMap { $0.image }
print(imageArray) // imageViewThree.image
If the extension does not work for your requirements, I would definitely consider "filter and flatMap" to avoid that if-statement.
I would recommend creating a new UI component for your needs with a background UIImageView(placeholder) and an optional foreground UIImageView (user selected). Then just check for the existence of the optional foreground UIImageView as you can rely upon this being the UIImageView containing the user chosen image.
Everything I google turns up answers about ALAsset's.
I have an images.xcassets folder and a bunch of assets in there.
I want to know if an asset exists in there based on a string.
E.g. if(images.xcassets.contains("assetName") == true)
Do you know how I can check if an asset exists based on a string?
This is one way to check it.
NSString *someString = #"SomeStringFromSomwhere";
if ([UIImage imageNamed: someString])
{
//the image exists..
}
else
{
//no image with that name
}
Just a bit more practical answer: Swift
if let myImage = UIImage(named: "assetName") {
// use your image (myImage), it exists!
}
Check whether image exist or not : Swift 3
if (UIImage(named: "your_Image_name") != nil) {
print("Image existing")
}
else {
print("Image is not existing")
}
I ended up with some combination of both and turned it into a function to use throughout my code. I also want to return a default image if the one provided is missing. (Swift 4 version)
func loadImage (named: String) -> UIImage {
if let confirmedImage = UIImage(named: named) {
return confirmedImage
} else {
return UIImage(named: "Default_Image.png")
}
}
Then to load the image into something like a button you do something like this.
buttonOne.setImage(loadImage(named: "YourImage.png"), for: .normal)
For Swift, this is what I ended up using to assign either an existing asset or a default system image:
myImageView.image = UIImage(named: "myAssetName") ?? UIImage(systemName: "photo")
// When former is nil, assigns default system image called "photo"