简体   繁体   中英

Reverse UILabel.text value

I've got a program that I'm finishing up that is a name generator. Right now it takes a random value from 2 separate arrays, concatenates them and displays the result as the label. text -- I want to have a button that reverses the label text (instead of John Doe, it would say Doe John). This is the code I'm using to do this. My thinking is that I use the same values from the arrays and then assign the string to a variable for use later in another method called "reverseNameValue" or something. It's not working :) When I click the "reverse" button, it shows me a different name altogether. Any advice?

- (IBAction)generateBName:(id)sender {
int a = arc4random() % 3;
int b = arc4random() % 3;


// populate the array for the names
NSArray *firstNameArray = [NSArray arrayWithObjects: @"Jacob",
                           @"Ethan",
                           @"Justin", nil];
NSArray *middleNameArray = [NSArray arrayWithObjects: @"Jose",
                            @"Jeremiah",
                            @"Julian", nil];

// concatenate strings at index of array
NSString *fullName = [NSString stringWithFormat:@"%@ %@", [firstNameArray objectAtIndex:a], [middleNameArray objectAtIndex:b]];
NSString *reverseName = [NSString stringWithFormat:@"%@ %@", [firstNameArray objectAtIndex:b], [middleNameArray objectAtIndex:a]];

// display the newly created first & middle names
reverseNameString = reverseName;
babyname.text = fullName;

And the reverse method:

- (IBAction)reverseLabel:(id)sender {
babyname.text = reverseNameString;
}

the line where you set the reverseName string has the names backwards, so it is grabbing a firstname and then a middlename but with reversed indexes. It should be:

 NSString *reverseName = [NSString stringWithFormat:@"%@ %@", [middleNameArray objectAtIndex:b],[firstNameArray objectAtIndex:a]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM