I'm trying to get a random number generator working on the iPhone. There are two text fields a label and a button. Enter the minimum number in one textfield and the maximum in the next. Clicking the button will display the random number in the UILabel. I did this once before and can't figure it out for the life of me today. Any code or places I could visit to find this out would be fantastic.
Thanks
Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.
NSString *min = myMinTextField.text; //Get the current text from your minimum and maximum textfields. NSString *max = myMaxTextField.text; int randNum = rand() % ([max intValue] - [min intValue]) + [min intValue]; //create the random number. NSString *num = [NSString stringWithFormat:@"%d", randNum]; //Make the number into a string. [myLabel setText:num]; // Give your label the value of the string that contains the number.
Update:
It appears that it is probably better to use arc4random
as opposed to rand
you can see more about it here. Just replace all the rand
s with arc4random
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With