I am pretty new to Swift and I cant find the answer to my issue with Swift.
Creating an lotto number generator and I can do it using a label but I'm having difficulties mapping these numbers to images (e.g. lotto ball images) so whenever numbers are populated, it will convert these numbers to images and shows in a custom Cell.
Currently using a tableView with customer Cell - i have six UIImageView in a cell.
Through out my practice, i found myself repeating the same codes. e.g. ball1.image = arc4Random_uniform(45) and ball2 ball3 and so on.. want to learn the harder way. i mean not repeating the codes. please masters how could i populate 6 numbers from 1-45 without duplicate and shows 6 lotto ball images in a cell?
To reduce code usage, make methods on the view controller and call it with the array of image views.
Here is the method:
func setImages(imageViews: [UIImageView]) {
var numSet = Set<Int>()
while numSet.count < imageViews.count
{
numSet.insert(Int(arc4random_uniform(45)) + 1) // Assuming you want numbers from 1 to 45 inclusive of both.
}
for (i, elem) in numSet.sort(<).enumerate() // Don't use sort if not needed.
{
imageViews[i].image = UIImage(named: "lotto\(elem).png") // Or whatever naming convention you used for the images.
}
}
Just call the setImages with the array of imageViews. It uses the count of the array to generate enough numbers. Don't forget to change the naming scheme used for the images. I assumed you used a naming scheme of lotto1.png, lotto2.png ... lotto44.png
Related
I'm confused about the coordinate.column and coordinate.row used in the code swift plyground provided below. How was column and row accssed when I didn't instantiate the instance coordinate? If the for loop insatntiate coordinate, how was it instantiated when allcoordinates or world.allPossibleCoordinates are not a type? (There are no parathenthesis around world.allPossibleCoordinates...)
let allCoordinates = world.allPossibleCoordinates
var blockSet: [Coordinate] = []
//#-editable-code Tap to enter code
for coordinate in allCoordinates {
// Check for coordinates with a column > 5 OR a row < 4.
if coordinate.column > 2 && coordinate.row < 5 {
// Append coordinate to blockSet.
}
}
In Swift, the for in loop works a bit differently than a for loop in other languages. A for in loop strides over a range (I'm assuming allCoordinates is strideable). In the provided example, if the variable allCoordinates is a strideable range, the loop will go through every single item in that range assigning each value to coordinate per iteration. For more information, have a look at Apple's Documentation
I’m a beginner in programming and playing around with the arc4random_uniform() function in Swift. The program I’m making so far generates a random number from 1-10 regenerated by a UIButton. However, I want the variable ’highest' that gets initialised to the random number to update if the next generated number is larger than the one currently held in it. For example the random number is 6 which is stored in highest and if the next number is 8 highest becomes 8. I don't know how to go about this. I have connected the UIButton to an IBAction function and have the following code:
var randomValue = arc4random_uniform(11) + 1
highest = Int(randomValue)
if (Int(randomValue) < highest) {
// Don’t know what to do
}
Initialise highest to 0
Every time you generate a new random number, replace the value of highest with the higher of the two numbers
highest = max(highest, randomValue)
The max() function is part of the Swift standard library and returns the larger of the two passed in vales.
edited to add
Here's a playground showing this with a bit more detail, including casting of types:
var highest: Int = 0
func random() -> Int {
let r = arc4random_uniform(10) + 1
return Int(r)
}
var randomValue = random()
highest = max(highest, randomValue)
You can see that multiple calls persist the highest value.
I have an array of objects. Each object has property "date" and "title".
I want to populate sectioned UITableView with those items like:
Section 1 - 2012.06.12 (taken from object.date)
Cell 1.1: Title 1 (taken from object.name)
Cell 1.2: Title 2
Cell 1.3: Title 3
...
Section 2 - 2012.06.13
Cell 2.1: Title 1
Cell 2.2: Title 2
..
Section 3 ..
I can do that by manually creating 1..n NSMutableArrays for all date combinations and filling them with object.name values. But the problem is I do not know how many date combinations there are, so it should be done dynamically. Also, the date property can repeat in different objects
My object structure is:
Object
-NSDate - date
-NSString - title
UPD:
I was thinking if it is possible to create NSDictionary, where the key would be my date and the object would be NSArray, which contains all my items for the key-date. But I do not know how to do that dynamically.
I hope I explained my question clearly enough.
Thank you in advance!
You can create arrays based on date.You have array of objects, so iterate through this array of objects to get distinct dates, as follows:
for(int i =0;i<[objectsArr count];i++)
{
if(![newDateArr containsObject:[objectsArr objectAtIndex:i].date])
{
[newDateArr addObject:[objectsArr objectAtIndex:i].date];
}
NSMutableArray *newTitleArray = [newTitleDictionary objectForKey:#"[objectsArr objectAtIndex:i].date"];
if(newTitleArray != nil)
{
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
else
{
newTitleArray = [[[NSMutableArray alloc] init] autorelease];
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
[newTitleDictionary setValue:newTitleArray forKey:#"[objectsArr objectAtIndex:i].date"];
}
where newTitleDictionary and newDateArr are declare outside this method.Now you can use both is newTitleDictionary and newDateArr to populate tableview.
If I understand you correctly, you want to put an object into an array and then use that array to populate a table view?
Just add the date object each time to the NSMutableArray.
[myArray addObject:dateObject];
Then when it comes to populating the table view..
DateObject *newDateObj = [myArray objectAtIndex:index];
I hope this helps and I understood your question
EDIT To answer now I understand a bit more.
Step 1
Check through the existing array of dates and see if there are any that match maybe by iterating through it using a for loop. Search online for how to compare NSDate.
Step 2 If it doesn't match any then insert it into the array as an array with just that date on it's own so the array count will be one. If it does match then insert it into the array along with that one making the array count 2 or more.
Step 3 When it comes to declaring the section amount for the table just return the dateHolderArray count.
Step 4 When declaring the amount of rows in each section, return the array count for the array thats inside the dateHolderArray.
Step 5 Display the content when it comes to populating the cells with information. It becomes just a task of getting the dates from the arrays using the section ids and row ids.
This is how I would do it, there are probably many other methods. Any questions just ask
I have a UIScrollView and five UIViewControllers A,B,C,D,E.
The order of the UIViewController views to be shown in the scroll view depends on some pre-requisite (e.g. one day it might be B,A,E,D,C and the next E,A,D,B,C and so on).
How can I keep track of which UIViewController is to be displayed (as in something like tags for each UIViewController which can be stored in an array and updated)?
Is it possible to assign views to the scroll view in the dynamic fashion shown above?
you want to make out a way to permutate the 5 view controllers ?
maybe it helps to use the property of prime numbers.
it depends on the count of permutations you want.
but since there's only 5 view controllers, there can't be more than 5! = 120 permutations
what's good about 5 is that it's a prime number
so if you calculate (n*a) % 5,where a is a constant number from 0 to 4, and n is a variable from 1 to 5 you get a table like this :
a==0, 0,0,0,0,0
a==1, 1,2,3,4,0
a==2, 2,4,1,3,0
a==3, 3,1,4,2,0
a==4, 4,3,2,1,0
as you've seen, that's 5 completely different permutations, in which each number appears exactly once.
so, if you want to have 120 permutations
just apply a const number b (from 0 to 4), and calculate (n*a + b) % 5
then you'll get 5 times the previous result, which is 125 , but there are some repetitions, then the final result will be 120 permutations.
so, the only thing you have to do is to determine a and b with your prerequisite
and apply the following code:
int result = (n*a + b)%5;
static UIView *addedView = nil;
if(addedView != nil)
[addedView removeFromSuperview];
switch(result)
{
case 0:
[self.scrollView addSubview:VCA.view];
addedView = VCA.view;
break;
case 1:
[self.scrollView addSubview:VCB.view];
addedView = VCB.view;
break;
//and so on...
}
hope it helps
Hi everybody: i want to take a picture and retrieve the main color analyzing its palette (i think this should be the easiest way), but i don't know really where to start.
Assuming you have a raw 24 bit RGB image and you want to find the number of times each color appears:
there are really 2 simple ways of doing this:
my favourite is just to create an array of ints for each possible color, then just index into that array and ++ that method does use like 64 meg of memory tho.
another method is to create a linked list, adding to it each time a new color is encountered, the structs stored in the list would store the color and the number of times encountered, its slow to do all the accumulating cause you have to search the whole list for each pixel, but it would be quicker to sort by number of times used, as only colors actually used are in the list (making it more ideal for small images too)
I like a compromise between the two:
take say, red and green to index into an array of linked lists, that way the array is only 256k (assuming it just stores a pointer to the list) and the lists to search will be relatively short because its only the blue variants of the Red,Green color. if you were only interested in the SINGLE MOST used color, I would just store this in a "max color" variable, that I would compare with each time I iterated over a pixel and incremented a color, that way you don't have to go through the whole structure searching for the most used at the end.
struct Pixel
{
byte R,G,B;
}
const int noPixels = 1024*768; // this is whatever the number of pixels you have is
Pixel pixels[noPixels]; // this is your raw array of pixels
unsinged int mostUsedCount = 0;
Pixel mostUsedColor;
struct ColorNode
{
ColorNode* next;
unsigned int count;
byte B;
}
ColorNode* RG = new ColorNode[256*256];
memset(RG,0,sizeof(ColorNode)*256*256);
for(int i = 0; i<noPixels; i++)
{
int idx = pixels[i].R + pixels[i].G*256;
ColorNode*t;
for(t=RG[idx]; t; t = t->next)
{
if(t->B == pixels[i].B)
{
break;
}
}
if(!t)
{
t = new ColorNode;
t->next = RG[idx];
RG[idx] = t;
t->B = pixels[i].B;
t->count = 0;
}
t->count++;
if(t->count > mostUsedCount)
{
mostUsedCount = t->count;
mostUsedColor = pixels[i];
}
}
you might consider using a Binary Tree, or Tree of some kind too, rather than just searching through a list like that. but I'm not too knowledgeable on that type of thing...
Oh yeah... I forgot about memory management.
you could just go through the whole array and delete all the nodes that need deleting, but that would be boring.
if possible, allocate all the memory you would possibly need at the beginning, that would be 256k + sizeof(ColorNode) *noPixels ~= 256 + 2 to 3 times the size of your raw image data.
that way you can just pull nodes out using a simple stack method, and then delete everything in one foul swoop.
another thing you could do is also add the nodes to another link list for ALL allocated nodes as well, this increases the iterating process, adds data to Color node, and just saves having to iterate through the entire array to find lists to delete.