The reason I ask is because I have a Dictionary of objects that I would like to populate my UITableView with. Since the Dictionary has objects for both the key and value, I'm unsure of how to populate the UITableView with it. The only way I know of to populate a UITableView is to use cellForRowAtIndexPath which requires an index (indexPath.row) and since my Dictionary is a collection of objects, I'm unable to reference each object by index.
Does anyone know if you can populate a UITableView without using cellForRowAtIndexPath method? Or, is there a way to populate the UITableView with the Dictionary of object by using cellForRowAtIndexPath?
As per my comment:
Dictionaries do not have a fixed order, so this would possibly yield different results on each run of the app.
So convert the dictionary to an array of the key/value tuples.
To convert a dictionary to an array (substitute your correct types as appropriate):
let dictionary = ["a" : 1, "b" : 2, "c" : 3]
var array = [(String, Int)]()
for tuple in dictionary {
array.append(tuple)
}
println(array)
Outputs:
[(b, 2), (a, 1), (c, 3)]
Related
I have this static dictionary created as so:
static var pictures = Dictionary<Int, Array<UIImage>>()
I want to populate it with images. At the moment when I am creating it I don't know how many key/value pairs I need to create. I have to fetch from the internet the data, but after that I am doing this to populate, but still my dictionary is empty:
for i in 0...Fetching.numberOfAliveListings - 1 {
for _ in 0...AdsCollectionView.listings[i].photos.count - 1 {
AdsCollectionView.pictures[i]?.append(UIImage(named: "noimage")!)
}
}
pictures is initially empty. So any attempt to access a value for a given key will result in a nil value. Since the value (the array) is nil, the optional chaining skips the call to append.
One solution is to provide a default array when looking up the value for a given Int.
AdsCollectionView.pictures[i, default: []].append(UIImage(named: "noimage")!)
You may also wish to consider alternate syntax when declaring pictures:
static var pictures = [Int: [UIImage]]()
I'm trying to convert a one dimensional array of UIButtons into a two dimensional array of them. In order to do this, I need to instantiate an empty two-dimensional array of UIButtons with nil values that I could then point to the respective UIButton in the one-dimensional UIButton array. I'm getting confused by Optionals since I'm new to Swift. Here's my one-dimensional array:
#IBOutlet var noteUIButtonArray: [UIButton]?
And I would like to convert this 128-size one-D array into a two-D [8][16] array of UIButtons with will values. How would I do this? Thanks in advance.
If an array value can be nil, then the type it is holding must be an optional type. You need a two-dimensional array of UIButton? which is just an array of array of UIButton? or [[UIButton?]].
Arrays have a handy initializer that takes the count of the items and the value you want to initialize with and creates the array. In your case, with a two-dimensional array, you will need to use this initializer twice: once for each row of the array and once for each column.
The inner initializer will create an array of 16 nil values:
let row:[UIButton?] = Array(count: 16, repeatedValue: nil)
The outer initializer will create an array of 8 rows:
var buttons2D:[[UIButton?]] = Array(count: 8, repeatedValue: row)
You typically nest both of these together to initialize a two-dimensional array like so:
var buttons2D:[[UIButton?]] = Array(count: 8, repeatedValue: Array(count: 16, repeatedValue: nil))
Note that the original array is an optional array of UIButton or [UIButton]?. This means that the array might not exist at all (it can be nil), or if it does exist it holds items of type UIButton. This array cannot hold nil values. When accessing a value in this array, you have to unwrap the array value. A safe way to do that is to use optional chaining.
For example, to access the first button in noteUIButtonArray, you'd write:
let button = noteUIButtonArray?[0]
The ? unwraps the optional array and allows you to access item 0. If noteUIButtonArray is nil, then the optional chain will be nil, so button will receive the value nil. Since button can receive nil, its type is UIButton?. So, even though the array can't hold optional values, you will receive an optional value from the optional chain which then will need to be unwrapped to use it.
Then you could loop through your array of 128 buttons an assign them to your 2D array:
if noteUIButtonArray?.count >= 128 {
var i = 0
for row in 0..<8 {
for col in 0..<16 {
buttons2D[row][col] = noteUIButtonArray?[i++]
}
}
}
else {
print("Warning: there aren't 128 buttons")
}
You might want to assign your buttons in a different order. This is just an example of one way to do it.
I'm actually learning swift in order to develop iOS apps. I'd like, as an exercise, to create and populate an empty array, that would be filled by using a textfield and a button on the storyboard.
var arr = []
// When button is pressed :
arr.append(textfield.text)
XCode tells me that the append method is not a method of NSArray. So I have used the addObject one, but it is still not correct as the arr variable contains nil.
So here are my three questions :
Is it possible to create an empty array, and if so, how to populate it ?
Sometimes, in my ViewController, when I create a non-empty array, the append method is apparently not valid, and I don't understand why..
Finally, why even though I use the syntax :
var arr = [1] // For example
The arr object is NSArray object and not a NSMutableArray object, making it impossible to add/remove any object that is contained in it?
I hope my questions are clear, if not I'll upload more code of what I'm trying to build,
thank you for your answers !
Try to define your array as a String array, like this:
var arr: [String] = []
And then append to your list, either by:
arr.append("the string")
or
arr += ["the string"]
Empty array can be created using the following syntax.
var emptyArray = [String]()
emptyArray.append("Hi")
see this
You can use following also to add elements to your array.
//append - to add only one element
emptyArray.append("Hi")
//To add multiple elements
emptyArray += ["Hello", "How r u"]
emptyArray.extend(["am fine", "How r u"])
//Insert at specific index
emptyArray.insert("Who r u", atIndex: 1)
//To insert another array objects
var array1 = ["who", "what", "why"]
emptyArray.splice(array1, atIndex: 1)
I have a custom UITableViewCell, which contains a UIButton(upVoteButtonPressed) and a UILabel (voteScoreLabel).
In order to get the numerical scores to show up in the labels of the UITableView, the array that contains that the number of votes is a String array, although its contents are in actuality integers.
The tag of the label has been set in the tableview controller to be the same as the indexPath.row. This lets me pick a particular item in the array.
However when I want to add a specific value, add 1 for example, I cannot because when I try to execute the following code I get the following error: Int is not convertible to 'Range'.
The code below is in my custom UITableViewCell. My goal is to pick out a particular value of the array, convert it to an integer and then add 1 to it. What does this mean and how can I fix it.
#IBAction func upVoteButtonPressed(sender: AnyObject) {
groupVote[voteScoreLabel.tag]=groupVote[voteScoreLabel.tag].toInt()
}
Edit
The solution suggested in the comments to make the array type int, and then when putting into the tableview to convert to string has worked. Problem Solved.
Make the array type an int because the array is currently seen as a String type array and that is backwards and inefficient. Then when putting the array values into the UITableView use label.text = "(theIntValue)" to convert the int values into strings.
I have used a Table View with Dynamic Prototype cells.
I have created a sample row in the table view with four values of a quantity:
Title
Min Value
Max Value
Current value.
I have created Table view controller and table view cell classes for accessing those properties in my code.
Now I have to set the values dynamically. I can see people suggesting to pass array of values separately for each.
Like:
Array 1 for Title : which will display title for all items in the row
Array 2 for Min value and so on.....
Is there a way that we pass an array of objects to the table view and it creates the table.
Please suggest.
I can see people suggesting to pass array of values separately for each.
Don't do this it is very poor approach, instead create a single array of NSDictionnaries, for instance:
_listOfValue =
#[
#{#"Title":#"title 1", #"Min Value":#"0", #"Max Value":#"100", #"Current value":#"50"},
#{#"Title":#"title 2", #"Min Value":#"4", #"Max Value":#"90", #"Current value":#"60"},
#{#"Title":#"title 3", #"Min Value":#"6", #"Max Value":#"70", #"Current value":#"70"}
];
This will make it easy to retrieve the data you need since they are not separated.
In numberOfRowsInSection you can return [self.listOfValue count].
In cellForRowAtIndexPath or didSelectRowAtIndexPath you can easily get the dictionnary at the IndexPath then parse the value of each key.
//Get the specific value
NSDictionnary *valueDict = _listOfValue[indexPath.row];
//read data from value dictionary
valueDict[#"Title"];
//or the old syntax
[valueDict objectForKey:#"Title"];
No, you can't pass the array direct to the table. Your table view controller would usually maintain the array (often a single array containing dictionaries or custom class instances) and your code in the table view controller uses that array to configure the cells.