UIImage(named: String) or UIImage swift 4 - swift

What way is more convenient to set image from my app assets in my app Image View? I have two ways: the first one is function UIImage(named: String) or UIImage and both is working for me, but I want to know which one is the best ,so I can use one in the future
here is two examples
// first
let myImages1 = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]
#IBOutlet weak var diceImageView1: UIImageView!
diceImageView1.image = UIImage(named: myImages1[index1])
// second
let myImages2 = [ image1, image2, image3, image4, image5, image6 ]
#IBOutlet weak var diceImageView2: UIImageView!
diceImageView2.image = myImages2[index2]

We're using Images from assets catalog instead String names. It's the better way to set UIImage. But from swift 4.2 we can't use asset names anymore.
We should use image literal.
Here's the example:
let logoImageView: UIImageView = {
let iv = UIImageView()
// Set image with image literal
iv.image = #imageLiteral(resourceName: "feedback")
return iv
}()
Look at the screenshot below.
After you've typed Image Literal you can double click on that and choose your image from assets catalog. Here is the screenshot.
But last time I use this lib R.swift. Get strong typed, autocompleted resources like images, fonts and segues in Swift projects.
How it looks in code:

You can create an extension for UIImage and have static variables holding your images.
extension UIImage {
static var dice1: UIImage? {
return UIImage(named: "dice1")
}
}
let imageView = UIImageView()
imageView.image = UIImage.dice1
Or you can use image literals in Xcode which are nice because you can see the actual image

Related

Cannot assign value of type 'UIImage' to type 'UIImageView'

I am making a simple Personality Quiz where based on the results it will display a certain image into the ImageView on my Main Storyboard. In QuestionData.Swift I have used the following switch statement:
var image: UIImage { //personality image
switch self { //Checking what answer it matches to
case .open: return UIImage(named: "football.jpg")!
case .conscience: return UIImage(named: "football.jpg")!
case .extra: return UIImage(named: "football.jpg")!
case .agree: return UIImage(named: "football.jpg")!
case .neuro: return UIImage(named: "football.png")! //for testing purposes all images are the same
}
}
In my ResultsViewController:
#IBOutlet weak var resultsImage: UIImageView!
//function code goes here
resultsImage = mostCommonAnswer.image //matches image to personality result
I get the error 'Cannot assign value of type 'UIImage' to type 'UIImageView''
Any ideas how to fix this?
You need to set your image to UIImage property of UIImageView
resultsImage.image = mostCommonAnswer.image

Convert UIView to UIImage to save as binary data in Core Data

I am trying to save a UIView as a UIImage to save in the Core Data database. My code is causing a compile error at self.canVasView.image stating:
Value of type 'UIView' has no member 'image'.
I think part of this code works in Swift 4 but it is not working in Swift 5.
var canVasView = UIView()
#objc func hhh() {
let photo = self.canVasView.image
let data = UIImagePNGRepresentation(photo!)
if cdHandler.saveObject(pic: data!){
}
}
You need to use a specific subclass of UIView.
Try using:
var canVasView = UIImageView()
Of course, you need to actually set the .image property to some UIImage in order for the call to UIImagePNGRepresentation to actually work.

Using a vector image with TVMonogramView

I've looked around and unfortunately there's very little on the web about the latest addition to the tvOS 12.0 which is the TVUIKit and its new controls. I have a UICollectionView with UICollectionViewCells of the following type:
import UIKit
import TVUIKit
class AirportsCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
var airportView: TVMonogramView!
override func awakeFromNib() {
airportView = TVMonogramView(frame: self.contentView.frame)
airportView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(airportView)
}
}
I have some images in my assets catalog that are all PDF files and I've naturally checked the "Preserve vector data" and they work absolutely fine when I assign them to my UIImageView of choice with any given size. However, when I assign them to the image property of my TVMonogramView, I get a terrible quality on the images. They seem to have been rendered with a very low resolution.
Here's how I use them:
if let flag = UIImage(named: countryCode) {
cell.airportView.image = flag
} else {
cell.airportView.image = nil
}
How can I fix this behaviour and what is the alternative?

Show a GIF image using NSImageView

I want to show an animated gif image in my cocoa application.
I dragged the gif into Assets.xcassets in XCode. I was hoping that NSImageView can show a gif out of the box, so I tried the following code.
let imageView = NSImageView(frame: NSRect(x: 0, y: 0, width: 512, height: 512))
imageView.canDrawSubviewsIntoLayer = true
imageView.imageScaling = .ScaleNone
imageView.animates = true
imageView.image = NSImage(named: "loading-animation")
window.contentView?.addSubview(imageView)
The image does not show up. The above code works with a png image. How do I get this to work?
For me it works only if there is nothing set in the Attribute Inspector and with the code like that (hope, it will be useful for someone):
class FirstViewController: NSViewController {
#IBOutlet weak var imgImage1: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
let imgImage1 = NSImageView(frame: NSRect(x: 407, y: 474, width: 92, height: 74))
imgImage1.canDrawSubviewsIntoLayer = true
imgImage1.imageScaling = .scaleProportionallyDown
imgImage1.animates = true
imgImage1.image = NSImage(named: "mygif")
self.view.addSubview(imgImage1)
}
Enjoy :)
Xcode 12
Just add your gif file in your project (Not in Assets)
Add an NSImageView in your view controller.
Set the image name in the storyboard as your gif file name.
Tap on Animates property.
Answering my own question.
I was able to make a gif display in my app when I get the gif from a URL e.g.
imageView.image = NSImage(byReferencingURL: yourgifurl)
So, I figured there was something wrong with the way I copied the image into my project. Instead of putting the image in Assets.xcassets, I put it with the rest of source code and the gif shows up :) (but the animation speed seems to be very slow)
Suppose you have an animated gif resource named universe in an Assets.xcassets and NSImageView connected by IBOutlet named target:
...
#IBOutlet weak var target: NSImageView!
...
func applicationDidFinishLaunching(_ aNotification: Notification) {
...
target.animates = true
target.image = NSImage(data: NSDataAsset(name: "universe")!.data)
...
}
NOTE:
target.image = NSImage(named: "universe") // WILL NOT WORK!

NSAttributedString: image not showing up in UILabel

For some reason, the image does not display. I have dropped test.png and test#2x.png both under Image.xcassets/ I also dropped it within the project. None of that helped. Any assistance would be greatly appreciated.
var testView: UILabel = UILabel(frame: CGRectMake(20, 20, self.view.frame.width-40, self.view.frame.height-40))
var a = "Testing..."
var attachment = NSTextAttachment()
//This is the image that I would like to add
// I have dropped test.png and test#2x.png under Image.xcassets
attachment.image = UIImage(named: "test")
var attachmentString = NSAttributedString(attachment: attachment)
let attrsB = NSAttributedString(
string: "2nd line..Testing testing",
attributes: NSDictionary(
object: UIFont(name: "HelveticaNeue", size: 18.0)!,
forKey: NSFontAttributeName) as [NSObject : AnyObject])
a.appendAttributedString(attrsB)
let attributedTextToDisplay = NSMutableAttributedString(attributedString: a)
attributedTextToDisplay.appendAttributedString(attachmentString)
testView.attributedText = attributedTextToDisplay
self.view.addSubview(testView)
You need to allow your label to have multiple lines if you want to display more than 1 line.
var testView: UILabel = UILabel(frame: CGRectMake(20, 20, self.view.frame.width-40, self.view.frame.height-40))
testView.numberOfLines = 0;
Tips:
Use Storyboard & Interface Builder. WYSIWYG.
Use AutoLayout, it solves a lot of resizing for you
Use asserts if you are unsure of the content of a variable
Step into debugger and push on the eye icon to reveal quicklook
Eliminating all these variables will help you find out the root cause, and not worry, say, about whether or not your image is loaded. See sample below.
For good measures, I also explicitly typed a into a a:NSMutableAttributedString.
var a:NSMutableAttributedString
I had the issue when I used didSet {} on the IBOutlet, moving the code to ViewDidLoad() method solved it.