My UILabel is not displaying when my if statement is false - ios

I have a story board that has a UITextField, UIButton, UIImage, and UILabel to display the images in an array. If you type the correct name for the image file into a text field. So, the problem is that once the text field input does not match, it should update the UILabel to display "Result not found", but it doesn't.
#import "ViewController.h"
#interface ViewController ()
{
myClass *myNewClass;
NSMutableArray *picArray;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
picArray = [#[#"Button_Red",#"Button_Green"]mutableCopy];
}
- (IBAction)displayImageAction:(id)sender
{
NSString *titleSearched = self.textSearchField.text;
NSString *titleNotHere = self.notFoundLabel.text;
//Declare a bool variable here and set
BOOL variable1;
for (int i = 0; i < picArray.count; i++)
{
NSString *currentPic = picArray[i];
if ([titleSearched isEqualToString:currentPic])
{
variable1 = YES;
}
}
if (variable1 == YES) {
//this works fine displays the image
self.outputImage.image = [UIImage imageNamed: titleSearched];
[self.textSearchField resignFirstResponder];
} else {
//problem is here its not showing when input for the array is not equal it should display a message label "Result Not Found" but it remains blank on the IOS simulator
titleNotHere = [NSString stringWithFormat:#"Result Not found"];
[self.textSearchField resignFirstResponder];
}
}
//Get rid of the texfield when done typing
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// Retract keyboard if up
[self.textSearchField resignFirstResponder];
}

Your problem is that
titleNotHere = [NSString stringWithFormat:#"Result Not found"];
simply sets the method variable titleNotHere.
What you want is
self.notFoundLabel.text=#"Result Not found";
You will also want
self.notFoundLabel.text=#"";
when the result is found.

I think you will have to SET the value to the variable
self.notFoundLabel.text = [NSString stringWithFormat:#"Result Not found"]
or
self.notFoundLabel setText:[NSString stringWithFormat:#"Result Not found"]
UILabel.text = #"whatever..." is actually converted into [UILable setText:#"whatever..."].
NSString *labelText = UILabel.text has to be thought as NSString *labelText = [UILabel text];

This:
NSString *titleNotHere = self.notFoundLabel.text;
stores the text from the label into a variable, but updating that variable again will not change the label text - it only changes what that variable points to.
You need to explicitly update the label text:
self.notFoundLabel.text = #"Result Not found";
note also that this uses a string literal - you don't need to use a format string as you aren't adding any parameters to it.
Also, when checking booleans, don't use if (variable1 == YES) {, just use if (variable1) { (it's safer).

Related

How to pass value in uitextview using segue

I'm trying to create something in UITextView that every time the text encounter this kind of symbol "#". All text after that symbol will send to other controller.
here's my code
- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// "Length of existing text" - "Length of replaced text" + "Length of replacement text"
NSInteger newTextLength = [self.addingText.text length] - range.length + [text length];
if([text isEqualToString:#"#"] || secondString){
secondString = true;
NSString * stringToRange = [self.addingText.text substringWithRange:NSMakeRange(0,range.location)];
// Appending the currently typed charactor
stringToRange = [stringToRange stringByAppendingString:text];
// Processing the last typed word
NSArray *wordArray = [stringToRange componentsSeparatedByString:#"#"];
self.getSecondString = [wordArray lastObject];
// wordTyped will give you the last typed object
NSLog(#"\nWordTyped : %#",self.getSecondString);
}
if (newTextLength > 50) {
// don't allow change
[aTextView resignFirstResponder];
return NO;
}
self.countChar.text = [NSString stringWithFormat:#"%li", (long)newTextLength];
return YES;
}
I get that code from here. It is perfectly work when I use NSLog but the time I click the button to send it to other controller using segue. It always show Null value. Hoping your help here. Thanks in advance
here's my button code
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
CameraViewController * cameraViewController = (CameraViewController *)[segue destinationViewController];
if([segue.identifier isEqualToString:#"createText"]){
NSLog(#"prepareForSegue: %# == %#", self.addingText.text,self.getSecondString);
cameraViewController.inputCreateText = [NSString stringWithFormat:#"%#", self.addingText.text];
cameraViewController.secondInputCreateText =[NSString stringWithFormat:#"%#", self.getSecondString];
}
}
I think your problem is you are modifying your string inside textView:shouldChangeTextInRange: which gets called for every typed in character. If your purpose is to send the string after # on tap on a button then do the calculation on button handler or inside prepareForSegue:sender:. If for some reason you want to stick to your own implementation then I would advise to put your targeted string inside NSMutableArray property created at class level so you don't loose data. And then you can combine all string inside that array like this [arrayOfStrings componentsJoinedByString:#" "].

Expected Identifier

Please can anyone tell me why this piece of code isn't working? I've got a dictionary which contains UIViews with tables inside associated with the keys which are the names of the corresponding buttons (there are a lot of them). So what I actually want to do is to change the view visibility on the corresponding button click. But the issue is that the expression to do that is not accepted by Xcode and I get the Expected Identifier error.
- (IBAction)choosingButtonClicked:(id)sender {
if ([sender currentTitle]) {
[(UIView *)[self.selectionTables objectForKey:[sender currentTitle]]].hidden = ![(UIView *)[self.selectionTables objectForKey:[sender currentTitle]]].isHidden;
}
}
First of all, with all due respect, I agree with trojanfoe comments. Its not working because its not properly written.
Now, lets try to streamline it with below code:
- (IBAction)choosingButtonClicked:(id)sender {
NSString *title = [sender currentTitle];
if (title) {
UIView *selectionView = (UIView *)self.selectionTables[title];
selectionView.hidden = !selectionView.isHidden;
}
}
Your code is too complex, because of that even the author can't understand it. If we re-write your code using local variables, it will look like:
- (IBAction)choosingButtonClicked:(id)sender
{
NSString *title = [sender currentTitle];
if (title)
{
UIView *tempView = (UIView *)[self.selectionTables objectForKey:title];
[tempView].hidden = ![tempView].isHidden;
}
}
If you check the code now, you can see that the following code is causing the issues:
[tempView].hidden = ![tempView].isHidden;
Change your method like:
- (IBAction)choosingButtonClicked:(id)sender
{
NSString *title = [sender currentTitle];
if (title)
{
UIView *tempView = (UIView *)[self.selectionTables objectForKey:title];
tempView.hidden = !(tempView.isHidden);
}
}

How do I display an alternate message if an object does not exist in my array? Objective C

The object of this application is to translate between english and spanish words.
(Checks text input against all array values to see if it's there and then compares that index to the second array, and displays the parallel value).
That part is working. If the word entered does not exist in the array, I am supposed to have a message like 'No translation available' display in the label. My problem is, I can either get the message to display for nothing or everything - rather than just when it is supposed to.
#import "TranslatorViewController.h"
#interface TranslatorViewController ()
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (weak, nonatomic) IBOutlet UILabel *label;
- (IBAction)translate:(id)sender;
#property (nonatomic, copy) NSArray *english;
#property (nonatomic, copy) NSArray *spanish;
#end
#implementation TranslatorViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_textField.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//make the keyboard go away
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
{[textField resignFirstResponder];}
return YES;
}
- (instancetype)initWithCoder:(NSCoder*)aDecoder {  self = [super initWithCoder:aDecoder]; if(self) {  // Add your custom init code here
self.english = #[#"phone",
#"dog",
#"sad",
#"happy",
#"crocodile"];
self.spanish = #[#"telefono",
#"perro",
#"triste",
#"felize",
#"cocodrilo"];
}  return self; }
- (IBAction)translate:(id)sender {
//loop through the array
NSString *englishWord = self.textField.text;
for (int index=0; index<[self.english count]; index++)
if([[self.english objectAtIndex:index]
isEqualToString:englishWord])
//retrieve the accompanying spanish word if english word exists in the array
{NSString *spanishWord = [self.spanish objectAtIndex:index];
//and display it in the label
self.label.text = spanishWord;}
//Need code to display 'no translation' if word was not found.
}
#end
The simplest way to do this is probably to set the label's text field to "No translation" before entering the loop. If no match is found, the label will never be re-set to anything else.
There are lots of other ways to structure logic to give you this result. I might tighten up that last loop of code by doing this instead:
NSString * englishWord = self.textField.text;
NSUInteger spanishWordIndex = [self.english indexOfObject:englishWord];
if (spanishWordIndex == NSNotFound) {
self.label.text = #"No translation";
} else {
self.label.text = self.spanish[spanishWordIndex];
}
Why not use an NSDictionary?
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
self = [super initWithCoder:aDecoder];
if(self) {  // Add your custom init code here
self.translationDict = #{#"phone":#"telefono",
#"dog":#"perro",
#"sad": #"triste",
#"happy": #"felize",
#"crocodile": #"cocodrilo"]; // self.translationDict is an NSDictionary
}
return self;
}
- (IBAction)translate:(id)sender {
NSString *englishWord = self.textField.text;
NSString *spanishWord=self.translationDict[englishWord];
if (spanishWord == nil) {
spanishWord="No Translation";
}
self.label.text=spanishWord;
}
I put
self.label.text = #"No translation available";
before the if statement which is I believe what Ben Zotto was trying to say! I just wasn't sure how to actually do it at first.
I'm a newb with this stuff.
But that did what I needed it to.
Thanks all!
Reformatted the answer to include your entire code. You should be able to just copy paste into your code.
- (IBAction)translate:(id)sender {
NSString *englishWord = self.textField.text;
NSString *spanishWord = #"No translation found.";
for (int index=0; index<[self.english count]; index++)
{
if([[self.english objectAtIndex:index] isEqualToString:englishWord])
{
//retrieve the accompanying spanish word if english word exists in the array
spanishWord = [self.spanish objectAtIndex:index];
}
}
self.label.text = spanishWord;
}

ibaction to switch text of two labels

I have two labels: oneLabel and twoLabel. Let's say oneLabel displays '1' and twoLabel displays '2'. I'm trying to create a button that when pressed will switch the text between the labels. I'm trying:
- (IBAction)switchButton:(id)sender {
self.oneLabel.text = self.twoLabel.text;
self.twoLabel.text = self.oneLabel.text;
}
The code switches twoLabel text to oneLabel, but not oneLabel text to twoLabel. What am I missing?
I think that is because after copying twoLabel's text to oneLabel; oneLable's text has twoLabel's text and when you try to copy the text from one to two ,one has two's content and that content only is copied to two so no change is seen in twoLable. Use breakpoints and check.Try
NSString *temp = self.oneLable.text;
self.oneLable.text= self.twoLable.text;
self.twoLable.text= temp;
Set 2 temporary strings>
NSString *myText1Str, *myText2Str;
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder]; //to hide the keyboard
[self setString]; //calling the method when u hit enter or return
return YES;
}
-(void)setString{ //this method sets the current string values from the textfield
myText1Str = self.oneLabel.text;
myText1Str = self.twoLabel.text;
}
-(IBAction)switchButton :(id)sender{ //swaps the texts
self.oneLabel.text = myText2Str;
self.oneLabel.text = myText1Str;
}
Try This
-(IBAction)btnClicked:(id)sender
{
NSString *str=lbl1.text;
NSString *str1=lbl2.text;
lbl1.text=str1;
lbl2.text=str;
}

UITextView textViewDidChangeSelection called twice

What I have :
TextView
NSArray (string)
AVAudioplayer (not yet implemented)
When I select a word in TextView :
• Check if word exist in Array
• Start Audioplayer with associated sound
Unfortunately when I tap twice to select a word inside TextView, textViewDidChangeSelection is called twice. I don’t know why I see "Youpie" twice.
I just changed inputView to hide keyboard because I only need TextView to be used in selecting mode.
- (void)textViewDidChangeSelection:(UITextView *)tve;
{
NSString *selectedText = [tve textInRange:tve.selectedTextRange];
if(selectedText.length > 0)
{
for (NSString *text in textArray)
{
if ([selectedText isEqualToString:text])
NSLog(#"Youpie");
tve.selectedTextRange = nil;
if (ps1.playing == YES)
{
[self stopEveryPlayer];
[self updateViewForPlayerState:ps1];
}
else if ([ps1 play])
{
[self updateViewForPlayerState:ps1];
fileName.text = [NSString stringWithFormat: #"%# (%d ch.)", [[ps1.url relativePath] lastPathComponent], ps1.numberOfChannels, nil];
}
else
NSLog(#"Could not play %#\n", ps1.url);
break;
}
}
}
}
- (void)awakeFromNib
{
textArray = [[NSArray alloc] initWithObjects:#"dog",#"cat",#"person",#"bird",#"mouse", nil];
textView.inputView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
textView.delegate = self;
// ...
}
I noticed something when I was double tapping on each good word in my text.
textViewDidChangeSelection
If a word is already selected and no action choosen, I have 1 "Youpie".
If not, I have 2 "Youpie".
I found a simple solution. I removed selectedRange after getting value. textViewDidChangeSelection called once.
What I have changed
tve.selectedTextRange = nil;
I use a subclass of UITextView to disable menu.
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
return NO;
return [super canPerformAction:action withSender:sender];
}
I added an implementation for AVAudioPlayer (ps1) too.
My "autoplay" is working if a known word is selecting :)
I don't have an answer for why the method gets called twice or how to prevent this, but an alternative solution might be to display an additional item in the edit menu that pops up in a text view when a word is double clicked. Then, your action for initiating a sound based on the word could be triggered from the action selector defined in that additional menu item. In this design, you'd remove your textViewDidChangeSelection and thus would not get called twice. See http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/AddingCustomEditMenuItems/AddingCustomEditMenuItems.html for some additional info about modifying the standard menu.

Resources