I have written some terrible code but it works. Is there a better way to write this? _decade.x are NSButtons.
int baseDecade = 1940;
NSString *title;
int currentDecade = 0;
- (IBAction)nameDecade:(id)sender {
currentDecade = baseDecade;
title = [NSString stringWithFormat: #"%ld", (long)currentDecade];
_decade1.stringValue = title;
currentDecade = currentDecade +10;
title = [NSString stringWithFormat: #"%ld", (long)currentDecade];
_decade2.stringValue = title;
currentDecade = currentDecade +10;
title = [NSString stringWithFormat: #"%ld", (long)currentDecade];
_decade3.stringValue = title;
In iOS you can put your buttons in a single IBOutletCollection in interface builder, or in an NSArray if you create your buttons through code. With that outlet collection / array in hand, you can use a loop to reference _decadeN by their index in the collection:
#property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *decadeButtons;
...
for (int i = 0 ; i != decadeButtons.count ; i++) {
UIButton * decade = decadeButtons[i];
NSString *title = [NSString stringWithFormat: #"%ld", (long)(baseDecade+10*i)];
decade.stringValue = title;
}
Edit: OSX does not support IBOutletCollections yet, so you would need to put _decadeN buttons in an array namually:
// I am using the new array literal syntax; using arrayWithObjects will work too.
NSArray *decadeButtons = #[_decade1, _decade2, _decade3];
// Use the same loop as above:
for (int i = 0 ; i != decadeButtons.count ; i++) {
UIButton * decade = decadeButtons[i];
NSString *title = [NSString stringWithFormat: #"%ld", (long)(baseDecade+10*i)];
decade.stringValue = title;
}
Related
The code below takes a string, adds each letter to an array and shuffles that array and shows the end result in a label. That works well. But I'd like for each character to contain a single character of the shuffled string. Right now it almost works, but it always repeats the characters. Like instead of having a series of 6 buttons with their titles: L e a g u e, the code generates repeated characters like: Leaauu.
My code is this:
- (IBAction)shuffleButttonTitles:(id)sender {
// The mutable array must be created here to create a new instance each time the button is tapped
letters = [[NSMutableArray alloc] init];
str = #"League";
length = str.length;
NSString *letter;
UIButton *button;
// First loop through the string and add each letter to an array
for (int i = 0; i < length; i++) {
letter = [NSString stringWithFormat:#"%c", [str characterAtIndex:i]];
[letters addObject:letter];
}
// Shuffle the string for the label/buttons
for (int i = 0; i < length; i++) {
int value = arc4random() % (length - 1);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
//Create the button and shuffle the letters for their titles
button = [[UIButton alloc] initWithFrame:CGRectMake(50 * i, 350, 44, 44)];
// HERE THE CODE REPEATS THE CHARACTERS
[button setTitle:[letters objectAtIndex:i] forState:UIControlStateNormal];
//Store the button in our array
[myButtons addObject:button];
NSLog(#"Letters in Array: %lu", letters.count);
}
for (UIButton *button in myButtons){
[button setBackgroundColor:[UIColor redColor]];
[self.view addSubview:button];
}
// Now we set the randomized title to the label
NSString *results = [letters componentsJoinedByString:#""];
string.text = results;
}
After some searching on the web I've figured it out. I post the complete code for others. This code takes a random string from the Characters.txt file and shuffles that string. Then it rotates the tiles slighty. You can enter the correct word when you have figured out the anagram, which then shows an alert view if you got it or didn't get it.
#define kTileSpacing 20
#define randomf(minX,maxX) ((float)(arc4random() % (maxX - minX + 1)) + (float)minX)
#interface ViewController ()
#end
#implementation ViewController
{
}
#synthesize progressView;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Anagrams" ofType:#"plist"];
dictionary = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSString *quotesFile = [[NSBundle mainBundle] pathForResource:#"Characters" ofType:#"txt"];
fileContents = [NSString stringWithContentsOfFile:quotesFile encoding:NSUTF8StringEncoding error:NULL];
// [txtField becomeFirstResponder];
//[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(checkWord:) name:nil object:nil];
}
- (IBAction)clear:(id)sender {
quoteArray = [fileContents componentsSeparatedByString:#"\n"];
NSString *quoteToDisplay;
currentQuestion = arc4random() % quoteArray.count;
quoteToDisplay = [quoteArray objectAtIndex: currentQuestion];
welldone.text = quoteToDisplay;
txtField.text = nil;
[txtField becomeFirstResponder];
for (UILabel *lbl in myButtons) {
[lbl removeFromSuperview];
}
}
- (IBAction)ShuffleString:(id)sender {
[self clear:nil];
// The mutable array must be created here to create a new instance each time the button is tapped
charactersArray = [[NSMutableArray alloc] init];
indexArray = [[NSMutableArray alloc] init];
myButtons = [[NSMutableArray alloc] init];
// 1. Shuffle the plist with the words to form anagrams from
currentQuestion = arc4random() % quoteArray.count;
str = [quoteArray objectAtIndex: currentQuestion]; //[[dictionary objectAtIndex:currentQuestion] objectForKey:#"Anagram"];
length = str.length;
NSString *letter;
// 2. Loop throught the chosen word and break it down into its letters and add them to an array
for (int i = 0; i < str.length; i++) {
// [charactersArray removeObjectAtIndex:i];
letter = [NSString stringWithFormat:#"%c", [str characterAtIndex:i]];
[charactersArray addObject:letter];
// NSLog(#"Number of letters: %#", charactersArray);
}
while ([charactersArray count]) {
int randomizing = arc4random() % [charactersArray count];
[indexArray addObject:[charactersArray objectAtIndex:randomizing]];
[charactersArray removeObjectAtIndex:randomizing];
// NSLog(#"NO REPEAT SHUFFLE: %lu", (unsigned long)indexArray.count);
}
/***************/
CGFloat staticY = self.view.bounds.size.height / 9 * 1; // Static X for all buttons.
CGFloat staticWidth = 46; // Static Width for all Buttons.
CGFloat staticHeight = 46; // Static Height for all buttons.
CGFloat staticPadding = 10; // Padding to add between each button.
float tileSize = ceilf( self.view.bounds.size.width / str.length );
NSLog(#"size %f", tileSize);
CGFloat xOffset = (self.view.bounds.size.width - str.length * (44+staticPadding));
NSLog(#"xOffset %f", tileSize);
xOffset = tileSize/ 2;
for (int i = 0; i < str.length; i++) {
singleCharacterLabel = [[UILabel alloc] init];
singleCharacterLabel.textAlignment = NSTextAlignmentCenter;
singleCharacterLabel.font = [UIFont fontWithName:#"Verdana-Bold" size:21];
singleCharacterLabel.frame = CGRectMake((staticPadding + (i * (staticHeight + staticPadding))), staticY, staticWidth, staticHeight);
// NSLog(#"X: %f", (staticPadding + (i * (staticHeight + staticPadding))));
//singleCharacterLabel.center = CGPointMake(i * 50 + self.view.bounds.origin.x + self.view.bounds.size.width /3, 80); // i * int +self... int = space between labels. Here it is '50'
// singleCharacterLabel.center = CGPointMake(self.view.bounds.size.width * i, self.view.bounds.size.height / 5 * 1); // 1/4th down from the top
singleCharacterLabel.layer.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Tile.png"]].CGColor;
NSString *anagramString = [indexArray objectAtIndex:i];
singleCharacterLabel.text = anagramString;
[myButtons addObject:singleCharacterLabel];
//1
//set random rotation of the tile
//anywhere between -0.2 and 0.3 radians
float rotation = randomf(0,50) / (float)100 - 0.2;
singleCharacterLabel.transform = CGAffineTransformMakeRotation( rotation );
//2
//move randomly upwards
int yOffset = (arc4random() % 10) - 10;
singleCharacterLabel.center = CGPointMake(singleCharacterLabel.center.x, singleCharacterLabel.center.y + yOffset);
[self.view addSubview:singleCharacterLabel];
//NSLog(#"LOOP: %#", anagramString);
}
}
- (IBAction)checkWord:(id)sender {
if (([txtField.text isEqual:str])) {
alertCorrect = [[UIAlertView alloc] initWithTitle:#"" message:#"Well done!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Next", nil];
[alertCorrect show];
} else {
alertWrong = [[UIAlertView alloc] initWithTitle:#"" message:#"Sorry, try again." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertWrong show];
}
// NSLog(#"String is: %lu", str.length);
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView == alertCorrect) {
if (buttonIndex == 0) {
[self ShuffleString:nil];
NSLog(#"next");
}
}
if (alertView == alertWrong) {
if (buttonIndex == 1) {
// Wrong answer. Close view and let user try again
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (txtField.text.length == length) {
[self checkWord:nil];
NSLog(#"You entered %lu characters", length);
}
return YES;
}
I am searching into a UITableView using this:
titles = [NSArray arrayWithArray:[datamanager titlesForEntriesBetween:(NSInteger)[slider minSelectedValue] and:(NSInteger)[slider maxSelectedValue]containing:searchText]];
How can I encode array value with NSASCIIStringEncoding during the search process?
(Array contains "tête" for example.. and when I search "tete" nothing matches.. so I will encode array value just for my search)
I would add change the third parameter to your datamanager function:
- (NSArray*)titlesForEntriesBetween:(NSInteger)startIndex
and:(NSInteger)stopIndex
withFunction:(BOOL(^)(NSString*))block {
NSMutableArray *retVal = [NSMutableArray array];
for(NSInteger i = startIndex; i <= stopIndex; ++i) {
NSString *string = [array_ objectAtIndex:i];
if (block(string)) {
[retVal insertObject:string];
}
}
return retVal;
}
And then I would call the function like this:
titles = [datamanager titlesForEntriesBetween:(NSInteger)[slider minSelectedValue] and:(NSInteger)[slider maxSelectedValue] withFunction:^(BOOL)(NSString *str) {
NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding];
NSString *simpleString = [[[NSString alloc] initWithData:data usingEncoding: NSASCIIStringEncoding] autorelease];
return [simpleString isEqualToString:str];
}]];
Note: I just typed this in, I haven't tried to compile/run this.
I have the following code which I would like to use to check user answers and output a score (out of 5). I use a plist with the answers in and check the textField.text against it. What I'm struggling with is: how to get an output score as a total using this method?
- (IBAction)checkAnswers:(UITextField *)textField
{
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"7A Cells Microscopes 3" ofType:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path2];
NSString *tester = [NSString stringWithFormat:#"%i", textField.tag];
// NSDictionary *secondDict = [dictionary valueForKey:tester];
// NSString *answer = [secondDict valueForKey:#"Answer"];
// if ([textField.text isEqualToString:[[dictionary valueForKey:tester] valueForKey:#"Answer"]]) {
// NSLog(#"YAY");
// }
NSArray *allTextFields = [[NSArray alloc] initWithObjects:eyepiece, objectiveLens, focussingKnobs, stage, mirror, nil];
for (textField in allTextFields) {
int x = 0;
if ([textField.text isEqualToString:[[dictionary valueForKey:tester] valueForKey:#"Answer"]]) {
x++;
NSLog(#"%i", x);
}
}
Any help would be much appreciated!
Many thanks.
Assuming the rest of your code is good, just move int x = 0; outside the for loop. The way you have it coded x is reset to 0 on every loop... so it never counts.
How do I add multiple strings to a string ?
Whats the easiest way to do that ?
If I don't want to create a new line of code every time I add something to a string, I'd like to do something like that :
NSString *recipeTitle = [#"<h5>Recipe name: " stringByAppendingFormat:recipe.name, #"</h5>"];
NSLog(#"%#", recipeTitle);
// This shows: <h5>Recipe name: myrecipe
// Where's the </h5> closing that header ? It will only show up with the next line of code
recipeTitle = [recipeTitle stringByAppendingFormat:#"</h5>"];
//my problem is that will result in more than 1k lines of programming
Do I have to necessarily add a new line appending the appended every time ?
Is there a faster/more productive way to do that ?
I'm trying to compose the email body with my tableview in it and that will result in a huge set of programming lines. Isthere anybody that could give me any hint or anything better than composing a huuuge string just so i can populate my email body with a table containing my tableview data ?
Any help to make this more productive is appreciated. Thanks !
Carlos Farini.
// After working on it a bit i got:
-(IBAction)sendmail{
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
[composer setMailComposeDelegate:self];
NSString *recipeTitle = #"<h5>Recipe name: ";
recipeTitle = [recipeTitle stringByAppendingFormat:recipe.name];
recipeTitle = [recipeTitle stringByAppendingFormat:#"</h5>"];
NSString *ingredientAmount = #"";
NSString *ingredientAisle = #"";
NSString *ingredientTitle = #"";
NSString *tableFirstLine = #"<table width='90%' border='1'><tr><td>Ingredient</td><td>Amount</td><td>Aisle</td></tr>";
NSString *increments = #"";
int i=0;
for (i=0; i < [ingredients count]; i++) {
Ingredient *ingredient = [ingredients objectAtIndex:i];
ingredientTitle = ingredient.name;
ingredientAmount = ingredient.amount;
ingredientAisle = ingredient.aisle;
increments = [increments stringByAppendingFormat:recipeTitle];
increments = [tableFirstLine stringByAppendingFormat:#"<tr><td>"];
increments = [increments stringByAppendingFormat:ingredientTitle];
increments = [increments stringByAppendingFormat:#"</td><td>"];
increments = [increments stringByAppendingFormat:ingredientAmount];
increments = [increments stringByAppendingFormat:#"</td><td>"];
increments = [increments stringByAppendingFormat:ingredientAisle];
increments = [increments stringByAppendingFormat:#"</td></tr>"];
if (i == ([ingredients count]-1)) {
//IF THIS IS THE LAST INGREDIENT, CLOSE THE TABLE
increments = [increments stringByAppendingFormat:#"</table>"];
}
}
NSLog(#"CODE:: %#", increments);
if ([MFMailComposeViewController canSendMail]) {
[composer setToRecipients:[NSArray arrayWithObjects:#"123#abc.com", nil]];
[composer setSubject:#"subject here"];
[composer setMessageBody:increments isHTML:YES];
[composer setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:composer animated:YES];
[composer release];
}else {
[composer release];
}
}
But then again, it's showing just one row in the table. What am I doing wrong here ?
How about something like this:
NSString *recipeTitle = [NSString stringWithFormat:#"<h5>Recipe name: %# </h5>", recipe.name];
I'm looking for a quick and easy way to strip non-alphanumeric characters from an NSString. Probably something using an NSCharacterSet, but I'm tired and nothing seems to return a string containing only the alphanumeric characters in a string.
We can do this by splitting and then joining. Requires OS X 10.5+ for the componentsSeparatedByCharactersInSet:
NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:#""];
In Swift, the componentsJoinedByString is replaced by join(...), so here it just replaces non-alphanumeric characters with a space.
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
let strippedReplacement = " ".join(someString.componentsSeparatedByCharactersInSet(charactersToRemove))
For Swift2 ...
var enteredByUser = field.text .. or whatever
let unsafeChars = NSCharacterSet.alphanumericCharacterSet().invertedSet
enteredByUser = enteredByUser
.componentsSeparatedByCharactersInSet(unsafeChars)
.joinWithSeparator("")
If you want to delete just the one character, for example delete all returns...
enteredByUser = enteredByUser
.componentsSeparatedByString("\n")
.joinWithSeparator("")
What I wound up doing was creating an NSCharacterSet and the -invertedSet method that I found (it's a wonder what an extra hour of sleep does for documentation-reading abilities). Here's the code snippet, assuming that someString is the string from which you want to remove non-alphanumeric characters:
NSCharacterSet *charactersToRemove =
[[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];
NSString *trimmedReplacement =
[ someString stringByTrimmingCharactersInSet:charactersToRemove ];
trimmedReplacement will then contain someString's alphanumeric characters.
Swift 3 version of accepted answer:
let unsafeChars = CharacterSet.alphanumerics.inverted
let myStrippedString = myString.components(separatedBy: unsafeChars).joined(separator: "")
Swift 5, Extension:
extension String {
/// Will strip all non alpha characters from a string
public var alpha: String {
return components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
}
}
A Cleanup Category
I have a method call stringByStrippingCharactersInSet: and stringByCollapsingWhitespace that might be convenient to just drop-in.
#implementation NSString (Cleanup)
- (NSString *)clp_stringByStrippingCharactersInSet:(NSCharacterSet *)set
{
return [[self componentsSeparatedByCharactersInSet:set] componentsJoinedByString:#""];
}
- (NSString *)clp_stringByCollapsingWhitespace
{
NSArray *components = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self <> ''"]];
return [components componentsJoinedByString:#" "];
}
#end
Here’s a Swift version of Cameron’s category as an extension:
extension String {
func stringByStrippingCharactersInSet(set:NSCharacterSet) -> String
{
return (self.componentsSeparatedByCharactersInSet(set) as NSArray).componentsJoinedByString("")
}
func stringByCollapsingWhitespace() -> String
{
var components:NSArray = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let predicate = NSPredicate(format: "self <> ''", argumentArray: nil)
components = components.filteredArrayUsingPredicate(predicate)
return components.componentsJoinedByString(" ")
}
}
The plain cycle would be the faster execution time I think:
#implementation NSString(MyUtil)
- (NSString*) stripNonNumbers {
NSMutableString* res = [NSMutableString new];
//NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
for ( int i=0; i < self.length; ++i ) {
unichar c = [self characterAtIndex:i];
if ( c >= '0' && c <= '9' ) // this looks cleaner, but a bit slower: [numericSet characterIsMember:c])
[res appendFormat:#"%c", c];
}
return res;
}
#end
This is a more effective way than the provided answer
+ (NSString *)alphanumericString:(NSString *)s {
NSCharacterSet * charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSMutableString * ms = [NSMutableString stringWithCapacity:[s length]];
for (NSInteger i = 0; i < s.length; ++i) {
unichar c = [s characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[ms appendFormat:#"%c", c];
}
}
return ms;
}
or as a Category
#implementation NSString (Alphanumeric)
- (NSString *)alphanumericString {
NSCharacterSet * charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSMutableString * ms = [NSMutableString stringWithCapacity:[self length]];
for (NSInteger i = 0; i < self.length; ++i) {
unichar c = [self characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[ms appendFormat:#"%c", c];
}
}
return ms;
}
#end