This is my code in swift 4 xcode. i have problems with my code. I can't show my array, with images on the simulator what things I'm doing wrong?
im a beginner in swift. and i have tried too look up how you write an array with images with four loop but the simulator docent show
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let img : UIImage = UIImage(named: "owl")!
let imageView = UIImageView(image: img )
self.view.addSubview(imageView)
// var images = Array<UIImage>()
//images.append(UIImage(named: "lion")!,
let ImgArray = ["lion.png","wolf.png","snake.png"]
var images = [UIImage]()
for i in 0..<ImgArray.count
{
images.append(UIImage(named: ImgArray[i])!)
}
let imageView2 = UIImageView(image: img )
self.view.addSubview(imageView2)
}
}
As explained by #Robert, instead of using the index of the array, you can use a for loop this way :
let imagesNames = ["img1.png", "img2.png", "img3.png"]
for imageName in imagesNames {
let image = UIImage(named: imageName)
images.append(image)
}
You can also use map to directly transform your array of images names to an array of images :
let imagesNames = ["img1.png", "img2.png", "img3.png"]
let images = imagesNames.map { UIImage(named: $0) }
where 0$ is your imageName.
Related
My swift codes goal is to create a array of images appended from a tableview cell. The code works however if the image is repeated twice. Right now sc.jpg is repeated twice in the array somepics when the code is appended. What prints out is gwen.jpg, kids.jgp, and sc.jpg only once. I want sc.jpg to appear twice in the array just like how it is in array somepics.
var arrayThatStartsEmpty = [UIImage]()
var somePics: [UIImage] = [UIImage(named: "gwen.jpg")!, UIImage(named: "kids.jpg")!, UIImage(named: "sc.jpg")!, UIImage(named: "sc.jpg")!]
#objc func collect(){
let collect = (0..<arr.count).compactMap { (theTable.cellForRow(at: IndexPath(row: $0, section: 0)) as? customtv)?.pic }
let arrayValues2 = collect.compactMap { $0.image }
arrayThatStartsEmpty.append(contentsOf: arrayValues2)
print(arrayValues2)
}
I made some changes on your collect() method. You can give it a try
#objc func collect(){
let collect = arr.enumerated().compactMap { (index, _) in
(theTable.cellForRow(at: IndexPath(row: index, section: 0)) as? customtv)?.pic }
let arrayValues2 = collect.compactMap { $0.image }
arrayThatStartsEmpty.append(contentsOf: arrayValues2)
print(arrayValues2)
}
I'm new to Swift and got stuck on something I've been experimenting.
Big picture:
I want to set up an app where I will have a set of images and when you press on an image it will produce a specific sound allocated to it.
Problem:
I have an array of images in the collectionView and was hoping that if I could automatically assign a tag to the images consecutively then I could line up the sounds according to the tag and link the sound to the image that way.
I have been playing around with the tag assignments for a few hours now and can't seem to be able to do it. The best I've got is set out below, could anyone help?
import UIKit
import AVFoundation
class basicVocabViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
#IBOutlet weak var collectionView: UICollectionView!
var audioPlayer:AVAudioPlayer?
let cards = ["1", "2", "3", "4"]
let cardImages: [UIImage] = [
UIImage(named: "1")!,
UIImage(named: "2")!,
UIImage(named: "3")!,
UIImage(named: "4")!,
]
// Assign tag to each UIImage
var cardImages.tag = 0
var currentTag = 0
for counter in cardImages {
let firstImage.tag = currentTag
currentTag += 1
}
}
You can only assign tag on a UIView. So, use UIImageView to set a tag. Just use a loop for the array of UIImageView as follows:
let cardImageViews = [UIImageView]()
for (index, imageView) in cardImageViews.enumerated() {
imageView.tag = index
}
Cannot convert value of type 'UIImage' to expected argument type 'String'
I am trying to create a book, and if I type in the name of the picture I want in the UIImageView constructor which is "cup", my program executes correctly and displays the same picture on every page. If I try and do "imageNames[element]" to get all my pictures displayed depending on page within my for loop it says it can not convert UIImage to String
var imageNames: [UIImage] = [
UIImage(named: "open")!,
UIImage(named: "cup")!
]
for element in 0 ..< imageNames.count {
let vc = UIViewController()
vc.view.backgroundColor = randomColor()
//Where error is occurring!
let imageView = UIImageView(image: UIImage(named:
imageNames[element]))
vc.view.addSubview(imageView)
}
I would think that imageNames[element] would give me the String value in the array.
My goal is that when I open the book.... "open" picture is on the first page, and "cup" picture is on the second page.
Just use an array of strings rather than images
let imageNames = ["open", "cup"]
for imageName in imageNames { // no reason for an index based loop
let vc = UIViewController()
vc.view.backgroundColor = randomColor()
let imageView = UIImageView(image: UIImage(named: imageName))
vc.view.addSubview(imageView)
}
Or if you really want an array of images
let images = [
UIImage(named: "open")!,
UIImage(named: "cup")!
]
for image in images { // no reason for an index based loop
let vc = UIViewController()
vc.view.backgroundColor = randomColor()
let imageView = UIImageView(image: image)
vc.view.addSubview(imageView)
}
I am trying to retrieve pictures saved from the database (in this case I hard coded the exact picture I want from the database). I have two UIImage variables initiated: imageView and rawImage. imageView is using SDWebImage from FirebaseUI to load the image, but I don't know how to save it into a UIImage array.
rawImage is grabbing the data from the path of the exact image from Firebase. I am converting it to a UIImage but when I want to append it to my UIImage array, the application crashes.
class GalleryViewController:UIViewController{
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var rawImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
view.addVerticalGradientLayer(topColor: primaryColor, bottomColor: secondaryColor)
self.tabBarController?.tabBar.isHidden = true
retrievePicture()
}
func retrievePicture()
{
guard let user_email = Auth.auth().currentUser?.email else { return }
let storageRef = Storage.storage().reference()
// Reference to an image file in Firebase Storage
let reference = storageRef.child("\(user_email)").child("/top").child("1.jpg")
// UIImageView in your ViewController
let imageView: UIImageView = self.imageView
// Placeholder image
let placeholderImage = UIImage(named: "placeholder.jpg")
//UploadViewController.Clothing.top_images.append(<#UIImage#>)
// Load the image using SDWebImage
imageView.sd_setImage(with: reference, placeholderImage: placeholderImage)
// this is the code for the rawImage portion I described above
reference.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("Error \(error)")
} else {
let picture = UIImage(data: data!)
UploadViewController.Clothing.top_images.append(picture!)
}
}
// loading the image to the rawImage imageview
rawImage.image = UploadViewController.Clothing.top_images[0]
}
}
If you already load the images using SDWebImage then you can also append the image in your UIImage array with that.
Just use SDWebImage with a completed block like this
var arr_image = [UIImage]()
imageView.sd_setImage(with: reference_url, placeholderImage: UIImage(named: "placeholder.jpg"), options: options: [.highPriority]) { (img, error, cachtype, url) in
if img != nil{
arr_image.append(img) // append UIimage in array
}
}
You have overlooked force unwrapping optionals, and I propose to you to remove ! usage to avoid crashes, use following instead
reference.getData(maxSize: 1 * 1024 * 1024) { data, error in
guard let data = data else {
print(error?.localizedDescription ?? "Check remote url or service")
return
}
if let picture = UIImage(data: data) {
UploadViewController.Clothing.top_images.append(picture)
} else {
print("Invalid image data\n\(String(data: data, encoding: .utf8))")
}
}
or following if statement is safe
if error == nil && data != nil, let picture = UIImage(data: data!) {
UploadViewController.Clothing.top_images.append(picture)
}
You can also try path without leading slash, like so:
let reference = storageRef.child("\(user_email)/top/1.jpg")
I am new in swift. Who can help? I have array with 3 links how can i take one link from this array and show in UIImageView then second link and then third? I make with one link but not understand how i can make with array. Thnx.
class ViewController: UIViewController {
#IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
var image = UIImage()
var imageData: Data?
let links = ["http://s.ill.in.ua/i/gallery/950x0/2694/146192.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146190.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146202.jpg"]
let url = URL(string: links[0])
do {
imageData = try Data(contentsOf: url!)
}
catch {
print("error")
}
if let value = imageData {
image = UIImage(data:value)!
imgView.image = image
}
}
}
You can easily iterate through array like this:
for link in links {
// This will iterate through array, so you can do something specific on each step
let url = URL(string: link)
do {
imageData = try Data(contentsOf: url!)
}
catch {
print("error")
}
if let value = imageData {
image = UIImage(data:value)!
imgView.image = image
print("Updated imageView with \(link)!")
}
}
Just use this way :
let links = ["http://s.ill.in.ua/i/gallery/950x0/2694/146192.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146190.jpg","http://s.ill.in.ua/i/gallery/950x0/2694/146202.jpg"]
Take three different ImageView ( for a while ) or u can use tableview to show image and use following link : https://stackoverflow.com/a/37019507/3400991
for linkValue in links {
yourimageview.imageFromServerURL(urlString: linkValue as! String)
}
this is one of the way u can show image into your imageview.