0

I'm working on creating a rotation of 32 names using UILabels. How would I random rotate all 32 names?

TWcode
  • 813
  • 2
  • 13
  • 27
  • 1
    What do you mean by rotation? Animation of moving UILabels or just a random pick of one name out of 32? – Alexander Feb 07 '12 at 14:05
  • i have 32 names. i would like to press a button and have the name labels randomly change names. – TWcode Feb 07 '12 at 17:42

2 Answers2

2
- (IBAction)buttonPressed
{
     int randomInt = rand() % [nameArray count]; 
     [nameLabel setText:[nameArray objectAtIndex:randomInt]]
}

In your .h file you must have:

IBOutlet UILabel *nameLabel;

EDIT

I built this project and here is the exact code I used: This is the .h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UILabel *nameLabel;
    NSArray *nameArray;
}
- (IBAction)buttonPressed;

@end

This is the .m file:

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    nameArray = [[NSArray alloc] initWithObjects:@"name1", @"name2", @"name3", @"name4", @"name5", @"name6", nil];
}

- (IBAction)buttonPressed
{
    int randomInt = rand() % [nameArray count]; 
    [nameLabel setText:[nameArray objectAtIndex:randomInt]];
}

- (void)dealloc
{
    [super dealloc];
    [nameArray release];
    nameArray = nil;
}
@end

Make sure that both the UILabel and button actions are connected in interface builder.

Jaybit
  • 1,864
  • 1
  • 13
  • 20
  • How would I implement this? I have all my UILabels conected as outlets. – TWcode Feb 08 '12 at 14:10
  • I had that part figured out. I'm getting the error message "use of undeclared identifier 'nameArray'. – TWcode Feb 08 '12 at 18:23
  • Yeah you need to replace nameArray with the name of the array in which your storing your list of names. You also need to make sure that the array is declared in you header file to that button pressed can access it. So in your .h file add if you don't have it. NSArray *nameArray; or NSMutableArray *nameArray; – Jaybit Feb 08 '12 at 18:33
  • How do i store my list of names? – TWcode Feb 08 '12 at 18:59
  • To create an array of names just use this: nameArray = [[NSArray alloc] initWithObjects:@"Jason", @"Bob", @"Tom", nil]; Follow that format and you have your array of names – Jaybit Feb 08 '12 at 19:44
  • Ok now I'm getting error message 'Program received signal:"EXC_AIRTHMETIC" – TWcode Feb 09 '12 at 02:48
  • I am sorry. I make a mistake. Change it to this: nameArray = [[NSArray alloc] initWithObjects:@"name1", @"name2", @"name3", @"name4", nil]; I made that edit above. – Jaybit Feb 09 '12 at 03:19
  • I would need a some more information to help you out. If you would edit your post to include your .h and .m files I could take a look. Also when are you getting the error? Is it when you try to run it? or when you try to hit the button? And one other question are you using ARC (automatic reference counting)? – Jaybit Feb 09 '12 at 05:23
  • I am running ARC with storyboard. Error is happens when i hit the button. – TWcode Feb 09 '12 at 11:37
  • With ARC you don't don't need the dealloc method. Next you need to go into your storyboard and right click on your button. It should only be connected to one method, which would be buttonPressed. I use this exact code without the dealloc method using ARC and Storyboard. So the only problem I could see would be your button may be connected to the wrong method or connected to multiple methods. – Jaybit Feb 09 '12 at 16:23
  • I got it to work! Thanks for your help and patience. Quick question...is there a way to use the label's current text and when the button is pushed it would randomly change all 32 labels initWithObjects:@"name1" – TWcode Feb 09 '12 at 17:26
  • I don't really understand what your question is. But to get the current text out of the label just use [nameLabel text] that will return an NSString of the text in the UILabel. Are you trying to make it so it doesn't use the same name? – Jaybit Feb 09 '12 at 18:34
  • I have it setup were I can edit the UITextField(yes I changed from a UILabel). Once I have the all 32 UITextFields edited(type in name), I want the button to rotate randomly all 32 UITextFields names. – TWcode Feb 10 '12 at 00:54
  • What do you mean by rotate randomly? Switch the names around in all the textfields? Display a random name in a separate Label or textfield. Also if you want it to rotate through the names what would you want to do when it reaches the last name? Rotate through again? – Jaybit Feb 10 '12 at 00:58
  • Switch the names around in all the textfields – TWcode Feb 10 '12 at 01:43
1
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    NSMutableArray *nameArray;
    NSMutableArray *textFieldArray;
    UIScrollView *scrollView;
}
- (IBAction)buttonPressed;
- (void)addTextFields:(int)count;

// Random sort function for the shuffle method
int randomSort(id obj1, id obj2, void *context );
@end





#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // If you want to pre load values 
    nameArray = [[NSMutableArray alloc] initWithObjects:@"name1", @"name2", @"name3", @"name4", @"name5", @"name6", nil];

    // Initilize the array to contain all the textfields
    textFieldArray = [[NSMutableArray alloc] init];

    // inititlize and add the scrollview
    scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:scrollView];

    // Create and add the button to randomize the fields
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(self.view.frame.size.width/2 - 150, 20, 150, 50)];
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Randomize" forState:UIControlStateNormal];
    [scrollView addSubview:button];

    // method to create any number of textfields (currently sending number of items in nameArray)
    [self addTextFields:[nameArray count]];

}

- (void)addTextFields:(int)count
{
    // adjust these to get the size and positions you like
#define X_POSITION 20
#define TEXT_FIELD_WIDTH 300
#define TEXT_FIELD_HEIGHT 50

    // Where to place the first text field
    int yPosition = 90;
    for (int textFieldCount = 0; textFieldCount<count; textFieldCount++) {

        //Create and add the text field
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(X_POSITION, yPosition, TEXT_FIELD_WIDTH, TEXT_FIELD_HEIGHT)];
        [textField setTag:textFieldCount];
        [scrollView addSubview:textField];
        [textFieldArray addObject:textField];
        [textField setText:[nameArray objectAtIndex:textFieldCount]];

        // Where to place the next text field
        yPosition += (TEXT_FIELD_HEIGHT + 20);
    }

    // set the scroll view content size so it will fit all the text fields
    [scrollView setContentSize:CGSizeMake(self.view.frame.size.width, yPosition+TEXT_FIELD_HEIGHT+20)];
}

- (IBAction)buttonPressed
{
    // release and remove everyting from the name array
    [nameArray release];
    nameArray = nil;

    // reinitilize the name array
    nameArray = [[NSMutableArray alloc] init];

    // Loop through the textfields to get the names into the nameArray
    for (int textFieldCount = 0; textFieldCount<[textFieldArray count]; textFieldCount++) {
        [nameArray addObject:[[textFieldArray objectAtIndex:textFieldCount] text]];
    }

    // Randomly sort the names in the array
    [nameArray sortUsingFunction:randomSort context:nil];

    // Add the random names back into the text fields
    for (int textFieldCount = 0; textFieldCount<[textFieldArray count]; textFieldCount++) {
        [[textFieldArray objectAtIndex:textFieldCount] setText:[nameArray objectAtIndex:textFieldCount]];
    }
}

int randomSort(id obj1, id obj2, void *context ) {
    // returns random number -1 0 1
    return (arc4random()%3 - 1);
}

- (void)dealloc
{
    [super dealloc];
    [nameArray release];
    nameArray = nil;
}
Jaybit
  • 1,864
  • 1
  • 13
  • 20
  • Because all the the textFields will not fit on the screen. I needed a way to scroll through them. Also this code does not check for empty textfields. If you were to delete all the text in one of the textfields and hit the randomize button it would crash. – Jaybit Feb 10 '12 at 16:47
  • This works great! What I have made is I have 32 TextFields that I can tap and move around. So my question is how could this be modified to existing TextFields? If possible I would prefer to use the IBAction in a toolbar. – TWcode Feb 10 '12 at 16:48
  • Well to modify it to use your existing text fields you would just not use the addTextFields: method and you would just need to add your textfields into the textFieldArray. And as for the IBAction in a tool bar. you would just have to connected to the the (IBAction)buttonPressed function. Remove the code where I created the button. – Jaybit Feb 10 '12 at 16:56
  • Ok. I've figured out the button and took away the scrollview. I thought the scroll view wash't needed with the the ability to tap and drag the textfield. – TWcode Feb 10 '12 at 17:04
  • How do I add the UITextField in the .m ? – TWcode Feb 10 '12 at 17:09
  • .h IBOutlet UITextField *tex1; .m UIView *clearView = [[UIView alloc] initWithFrame:tex1.frame]; – TWcode Feb 10 '12 at 17:20
  • Did you list out 32 UITextFields? or did you use a collection? If you're not using a collection I would suggest it. http://stackoverflow.com/questions/6527762/iboutletcollection-set-ordering-in-interface-builder – Jaybit Feb 10 '12 at 17:24
  • Also if you have UITextField *tex1; In the .h to add them into an array you would just do NSMuatableArray *textFieldArray = [[NSMutableArray alloc] initWithObjects:tex1, tex2, nil]; – Jaybit Feb 10 '12 at 17:27
  • I would add these ' NSMuatableArray *textFieldArray = [[NSMutableArray alloc] initWithObjects:tex1, tex2, nil]; ' into the viewDidLoad? – TWcode Feb 10 '12 at 17:37
  • Yeah I think that should do it for you. – Jaybit Feb 10 '12 at 17:38
  • One more thing. I was thinking of creating several buttons that could limit the number of textfields to rotate...like (14 textFields). How would I go about doing that? – TWcode Feb 11 '12 at 18:32
  • would the buttons change the number of textfields that are visible to the user? – Jaybit Feb 14 '12 at 02:45
  • I would Like to have several UIButtons that I can use to rotate a certain number. Is there a way to hide the the textfields that are not being used? – TWcode Feb 14 '12 at 05:16
  • - (IBAction)textFieldLimit14{ if ([tex15 setHidden:YES]; [textFieldArray removeObject:tex15]; [tex16 setHidden:YES]; [textFieldArray removeObject:tex16]; ...} – Jaybit Feb 15 '12 at 16:04
  • also make sure that you add the textfields back in to the array when you click something like - (IBAction)textFieldLimit20{ if([textFieldArray indexOfObject:tex15]==NSNotFound) [textFieldArray addObject:tex15]; – Jaybit Feb 15 '12 at 16:13
  • Do I need to include anything else with the code you provided? – TWcode Feb 16 '12 at 01:08
  • Yes you just need to follow the concept. You need to hide the textfields that are not going to be used and remove them from the textFieldArray. And your going to make sure that the textfields you need are in the textfieldArray. – Jaybit Feb 16 '12 at 04:39
  • I have also added NSUserdefaults for saving textfields information. I'm getting this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil – TWcode Feb 17 '12 at 20:39
  • That is happening because one or more of the textfields are empty. You will need to check of empty textfields. – Jaybit Feb 18 '12 at 23:21
  • How do I check if the textfields are empty? – TWcode Feb 22 '12 at 15:39
  • [[textfield text] length] will tell you the number of characters in a textfield so if its 0 then the textfield is empty. – Jaybit Feb 22 '12 at 17:51