Default Image Isn't Displaying When Setting Image - swift

I am trying to set the default avatar image to a "ninja" image. Default image isn't showing however with this code. Not sure what is wrong.
ProfileService.showOtherUser(user: bet.sentToUser) { [weak self] (profile2) in
self?.profile2 = profile2
if (profile2?.imageURL == "") {
cell.userImage.image = UIImage(named: "ninja")
}else{
let imageURL = URL(string: ((profile2?.imageURL ?? "")))
cell.userImage.kf.setImage(with: imageURL)
}
}
}

Put your image in storyboard to your image view this way till you not change it programmatically it will remain the default one

Related

Light and dark mode in swift

I created images assets for dark and light mode called myImage. Set the image assets appearance to Any, Dark.
The problem this code gets the same image even if the mode is light or dark.
How can I get the code to select the correct image depending on light or dark mode?
Thanks for your help.
let image = UIImage(named: "image")
let asset = image?.imageAsset
let resolvedImage = asset?.image(with: traitCollection)
If let image = resolvedImage {
myButton.setImage(image, for: .normal)
}
let image = UIImage(named: "image") is usually all that is needed, if you setup your asset correctly. Make sure to have "Appearances" set to "Any, Dark", then add your images in the appropriate slots:
Find out the current used dark/light mode with:
if traitCollection.userInterfaceStyle == .light {
print("Light mode")
} else {
print("Dark mode")
}
Then I'd access the light/dark Images with different name: UIImage:(named: "myImageLightMode") and UIImage:(named: "myImageDarkMode")
Keep in mind that you can tint images like button images in the desired color like the following, when you don't want to create each icon on a different color:
if let originalImage = UIImage(named: "yourButtonImage") {
let tintedImage = originalImage.withRenderingMode(.alwaysTemplate)
customButton.setImage(tintedImage, for: .normal)
customButton.tintColor = UIColor.red
} else {
print("Image not found.")
}
The same can be done on UIImageView's with the extension:
extension UIImageView {
func setImageAndColor(image: UIImage, color: UIColor) {
let templateImage = image.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
}
access this with:
let imageView = UIImageView()
imageView.setImageAndColor(image: UIImage(named: "yourImage"), color: .red)

Taking a snapshot of UIImageView instead of main View

I have in my app in my View a Button for taking snapshot with below code
open func takeScreenshot(_ shouldSave: Bool = true) -> UIImage? {
var screenshotImage :UIImage?
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
guard let context = UIGraphicsGetCurrentContext() else {return nil}
layer.render(in:context)
screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = screenshotImage, shouldSave {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
return screenshotImage
}
But in the same View is UIImageView and I want to take a snapshot of this UIImageView. How should I change the code? When I take a snapshot with this code, it will save only black screen with button for play/pause video and with button for taking snapshot.
Instead you using
let layer = UIApplication.shared.keyWindow!.layer
Just use your imageview Layer
let layer = YourImageView.layer

SDWebImage array url not appearing in uiimageview

I'm using SDWebImage for my Swift. I can't figure out why (frankly, HOW) it's not working. there is no image in imageview.
so this is what i'm trying. parse query PFFile(s) (url converted) stored in a var urlArray:[URL] = []
i have a UIScrollView with UIImageView inside.
in short: query parse - download PFFile URLs to an array (append).
for index in 0..<self.urlArray.count {
var frame = CGRect.zero
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
self.scrollView.isPagingEnabled = true
let subView = UIImageView(frame: frame)
subView.sd_setImage(with: self.urlArray[index], placeholderImage: #imageLiteral(resourceName: "profile"))
//subView.contentMode = .scaleAspectFit
self.scrollView.addSubview(subView)
}
first url image appears ok. then no pagination & no error (array numbers OK) just nothing apears but first pic. used this : imageview.sd_setImage(with: self.urlArray[index]) is this wrong approach?
thanks
I don't see the code where you update the contentSize of the UIScrollView. Unless you do that, the scroll view won't scroll for you. The additional image views may be there, but hidden outside of the scroll view's current bounds.
sdWebImage is a library using for image caching.
If you wanna detect error for downloading image by sdWebImage then you apply below code and track response from server.
cell.imageView.sd_setImageWithURL(NSURL (string: sendImgUri!), placeholderImage: UIImage (named: "pro.png"), options: .CacheMemoryOnly, progress: { (i, m) in
}, completed: { (image, error, chachType, url) in
if(error != nil)
{
print(error)
}
else if(image != nil)
{
print(image)
}
})

Change UIBarButtonIcon in an if and else statement in Swift

Inside of an If and else statement I want to change the custom image of my BarButtonItem. How can I Do these by default I already have one custom Image but know I want that under some circumstances it changes to another custom Image.
If you have your images in Assets.xcassets you can do this:
if something {
yourBarButtonItem.image = imagename
} else {
yourBarButtonItem.image = anotherimagename
}
that should work. Else, if you have your image just in a folder inside your project you can to this:
if something {
yourBarButtonItem.image = UIImage(named: "imagename.extension")
} else {
yourBarButtonItem.image = UIImage(named: "imagename.extension")
}

NSView dataWithPDF inside rect but with background view

I wan´t to take a screenshot of a NSView but when I do this, I get an image without the background. All the subviews are show, but not the background. I use this code:
if let image = NSImage(data: background.dataWithPDF(inside: background.bounds)) {
let imageView = NSImageView(image: image)
imageView.imageScaling = .scaleProportionallyUpOrDown
return NSImageView(image: image)
}
I thought, ok when I get only the subviews, then I will make a screenshot of the superview and I thried the following:
if let superview = background.superview, let image = NSImage(data: superview.dataWithPDF(inside: background.frame)) {
let imageView = NSImageView(image: image)
imageView.imageScaling = .scaleProportionallyUpOrDown
return NSImageView(image: image)
}
But I get the same result. Even if I set the background color of my background view I don´t get an image without transparent background.
How can I resolve this?
thank you
Artur
I got an Answer:
background.lockFocus()
if let rep = NSBitmapImageRep(focusedViewRect: background.bounds){
let img = NSImage(size: background.bounds.size)
img.addRepresentation(rep)
return NSImageView(image: img)
}
background.unlockFocus()
You could have converted the views backing layer.backgroundColor to an image. Then assign the image to a backing image view that sits in the 0th index of your views heirarchy and use the method dataWithPDF -> that will successfully capture a background.