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)
}
Related
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.
I have a model object called Hashtag. This simply contains a optional String variable called hashtagName. I fetch the data from my Firebase Database and append the hashtags to my fashionHashtags, which is a [Hashtag]. The issue I have is that I want to append that to my other categoriesArray by using the insertElementAtIndexPath function. I cannot do this as it wants an array of Strings and not an array of Hashtag. When I autocorrect it, it replaces it with fashionHashtags as! [String] but that creates another error. How do I fix this so it allows me to do so? I would like to stick to the Model Object way of doing things. Thank you guys. An answer would be highly appreciated. Code is below:
class Hashtag: NSObject {
vvar hashtagName: String?
}
private let reuseIdentifier = "Cell"
class HashtagView: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var catagoriesArray: [String] = ["FASHION", "FOOD", "HOBBIES", "MUSIC"]
var fashionHashtags = [Hashtag]()
var foodHashtags = [Hashtag]()
var hobbiesHashtags = [Hashtag]()
var musicHashtags = [Hashtag]()
var hashtagsArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.hashtagsArray.removeAll()
self.navigationController?.navigationBar.tintColor = .white
navigationItem.title = "Hashtag"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Finished", style: .plain, target: self, action: #selector(finishSelectingHashtags))
self.collectionView?.backgroundColor = .white
self.collectionView?.register(HashtagCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)
handleFetchFashionHashtags()
}
func insertElementAtIndexPath(element: [String], index: Int) {
catagoriesArray.insert(contentsOf: element, at: index)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
insertElementAtIndexPath(element: fashionHashtags, index: indexPath.item + 1)
self.collectionView?.performBatchUpdates(
{
self.collectionView?.reloadSections(NSIndexSet(index: 0) as IndexSet)
}, completion: { (finished:Bool) -> Void in
})
}
}
Based upon my understanding, there could be a couple of different approaches. Here would be the approach of looping through the array of Hashtag objects and appending the hashtagName string property to the categoriesArray of strings.
for hashTagItem in fashionHashtags {
if let hashTag = hashTagItem.hashtagName {
// Appends to categoriesArray as a string
categoriesArray.append(hashTag)
}
}
Another approach would be to build a set of strings and then insert it as it makes sense.
var hashTagString: [Strings] = []
for hashTagItem in fashionHashtags {
if let hashTag = hashTagItem.hashtagName {
hashTagStrings.append(hashTag)
}
}
// Insert or add the hash tag strings as it makes sense
categoriesArray += hashTagStrings // Add all at once if it makes sense
So the only way i can think of achieving this is by putting the array inside mainArray into a variable and then indexing that. Is there an easier way?
mainArray = [ 3400, "Overwatch", [UIButton(), UIButton()]] // Some buttons already made
currentButtonArray = mainArray[mainArray.count - 1] as! NSArray
for i in 0..<currentButtonArray.count {
buttonArray.append( currentButtonArray[i] as! UIButton)
}
If there is one array containing only UIButton instances, just filter it.
let mainArray : [Any] = [3400, "Overwatch", [UIButton(), UIButton()]]
if let buttonArray = mainArray.filter({$0 is [UIButton]}).first as? [UIButton] {
print(buttonArray)
}
or
let buttonArray = Array(mainArray.flatMap{$0 as? [UIButton]}.joined())
The second approach returns a non-optional empty array if there is no array of UIButton in mainArray
If the subarray is of all one type, you can append all in one go:
var buttonArray = [UIButton]()
let mainArray:[Any] = [3400, "Overwatch", [UIButton(), UIButton()]] // Some buttons already made
if let currentButtonArray = mainArray.last as? [UIButton] {
buttonArray.append(contentsOf: currentButtonArray)
}
Or you could simply write:
guard let currentButtonArray = mainArray.last as? [UIButton] else {
// do something e.g. return or break
fatalError()
}
// do stuff with array e.g. currentButtonArray.count
If you didn't know the position in the array of the nested UIButton array or if there were multiple nested button arrays then this would work:
let buttonArray = mainArray.reduce([UIButton]()){ (array, element) in if let bArray = element as? [UIButton] {
return array + bArray
}
else {
return array
}
}
Note: this is Swift 3 code.
I have a tableview that gets it's data from Parse via a queryForTable function. This works fine. I would like to get the same objects from Parse and add them to an array that I can later store in Core Data! Does anyone know how to do this? I have added my code below to show how I add it to a TableView.
Thanks for the help in advance. ;)
//MARK: Query for Table with the details
override func queryForTable() -> PFQuery {
let discoveryQuery = PFQuery(className: "DiscoveryDetails")
discoveryQuery.cachePolicy = .NetworkElseCache
discoveryQuery.whereKey("discoveryID", equalTo: PFObject(withoutDataWithClassName: "Discovery", objectId: "\(varInDDT!.objectId!)"))
discoveryQuery.orderByDescending("createdAt")
return discoveryQuery
}
....
//I strangely cannot find the type to declare that will hold all the
values that are shown in cellForRowAtIndexPath. PFObject does not seem
to work either. Maybe there is something I am missing about the
objects type that's universal to all.
var objectsArray : [String] = []
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
//Discovery Items TableViewCell
var discoveryDetailItemsCell:DiscoveryDetailTableViewCell! = tableView.dequeueReusableCellWithIdentifier("DiscoveryDetailTableViewCell") as? DiscoveryDetailTableViewCell
if (discoveryDetailItemsCell == nil) {
tableView.registerNib(UINib(nibName: "DiscoveryDetailTableViewCell", bundle: nil), forCellReuseIdentifier:"DiscoveryDetailTableViewCell")
discoveryDetailItemsCell = tableView.dequeueReusableCellWithIdentifier("DiscoveryDetailTableViewCell") as? DiscoveryDetailTableViewCell
}
//Background Colour of the Cell
discoveryDetailItemsCell.titleLabel.text = object?.objectForKey("exerciseName") as? String
discoveryDetailItemsCell.titleLabel.textColor = UIColor.whiteColor()
discoveryDetailItemsCell.durationAndSetsLabel.text = "\((object?.objectForKey("durationOrSets"))!)"
discoveryDetailItemsCell.minAndSetLabel.text = "mins"
discoveryDetailItemsCell.distanceAndRepsLabel.text = "\((object?.objectForKey("distanceOrReps"))!)"
discoveryDetailItemsCell.kmAndRepsLabel.text = "km"
discoveryDetailItemsCell.weightLabel.text = "\((object?.objectForKey("weight"))!)"
discoveryDetailItemsCell.kgsLabel.text = ""
discoveryDetailItemsCell.dot1.textColor = UIColor.grayColor()
discoveryDetailItemsCell.dot2.textColor = UIColor.grayColor()
//Load Images
let backgroundImage = object?.objectForKey("workoutImage") as? PFFile
discoveryDetailItemsCell.backgroundImageView.layer.masksToBounds = true
discoveryDetailItemsCell.backgroundImageView.layer.cornerRadius = 8.0
discoveryDetailItemsCell.backgroundImageView.image = UIImage(named: "loadingImage")
discoveryDetailItemsCell.backgroundImageView.file = backgroundImage
discoveryDetailItemsCell.backgroundImageView.loadInBackground()
//My Attempt at adding one of the values into an array
objectsArray = [(object?.objectForKey("exerciseName"))! as! String]
return discoveryDetailItemsCell
}
Trying to access and set my cells textLabel and detail text label to objects i have appended to the array. Im not to sure how to use the right syntax in this case. thanks for the help!
heres the objects I've appended from parse in my for loop.
var customers = [String]()
for object in objects {
self.customers.append(object["customerName"] as! String)
self.customers.append(object["customerStreetAddress"] as! String)
cellForRowAtIndexPath {
cell.textLabel.text = //I want the objects["customerName"] here
cell.detailTextLabel.text = // objects["customerStreetAddress"] here
}
You could try this.
var customers = [String]()
var number = -1
for object in objects {
self.customers.append(object["customerName"] as! String)
self.customers.append(object["customerStreetAddress"] as! String)
cellForRowAtIndexPath {
++number
if number + 1 <= customers.count {
cell.textLabel.text = customers[number]//I want the objects["customerName"] here
}
++number
if number + 1 <= customers.count {
cell.detailTextLabel.text = customers[number]// objects["customerStreetAddress"] here
}
}
}