comparing text of a button to a label in objective-c - objective-c

I have the following code:
int index = [self.colorlist count];
int random1 = (arc4random() % index);
NSString *color1 = [self.colorlist objectAtIndex:random1];
[Button1 setTitle:color1 forState:UIControlStateNormal];
I want to compare the Button 1 text to a different label with .isEqualTo but using
if button1.text isEqualToString: label
does not work. What is the proper syntax for calling button 1's text, rather than button1.text. Thanks!

There are two ways:
button.currentTitle
And
button.titleLabel.text
The first is a read-only reference to the current text on the button.
The latter is a readwrite reference to the text property of the label on the button. The label reference however (button.titleLabel) is itself readonly.

you can easily do it by following code
if([button.currentTitle isEqualToString(textField.text)])
{
//Succes part
}
else
{
//Failure Part
}
Hope this answer may help you

Related

How to do an on-item-changed for an NSPopUpButton?

I'm trying to implement a system that changes a label based on the state of an NSPopUpButton.
So far I've tried to do what's displayed in the code below, but whenever I run it, the code just jumps into the else clause, throwing an alert
- (IBAction)itemChanged:(id)sender {
if([typePopUp.stringValue isEqualToString: #"Price per character"]) {
_currency = [currencyField stringValue];
[additionalLabel setStringValue: _currency];
}
else if([typePopUp.stringValue isEqualToString: #"Percent saved"]) {
_currency = additionalLabel.stringValue = #"%";
}
else alert(#"Error", #"Please select a calculation type!");
}
So does anyone here know what to do to fix this?
#hamstergene is on the right track, but is comparing the title of the menu item rather than, say, the tag, which is wrong for the following reasons:
It means you cannot internationalize the app.
It introduces the possibility of spelling mistakes.
It's an inefficient comparison; comparing every character in a string takes way longer than comparing a single integer value.
Having said all that, NSPopUpButton makes it difficult to insert tags into the menu items, so you need to use the index of the selected item:
Assume you create the menu items using:
[typePopUp removeAllItems];
[typePopUp addItemsWithTitles: [NSArray arrayWithObjects: #"Choose one...", #"Price per character", #"Percent saved", nil]];
Then create an enum that matches the order of the titles in the array:
typedef enum {
ItemChooseOne,
ItemPricePerCharacter,
ItemPercentSaved
} ItemIndexes;
And then compare the selected item index, as follows:
- (IBAction)itemChanged:(id)sender {
NSInteger index = [(NSPopUpButton *)sender indexOfSelectedItem];
switch (index) {
case ItemChooseOne:
// something here
break;
case ItemPricePerCharacter:
_currency = [currencyField stringValue];
[additionalLabel setStringValue: _currency];
break;
case ItemPercentSaved:
_currency = #"%"; // See NOTE, below
additionalLabel.stringValue = #"%";
break;
default:
alert(#"Error", #"Please select a calculation type!");
}
}
NOTE the following line was incorrect in your code:
_currency = additionalLabel.stringValue = #"%";
Multiple assignment works because the result of x = y is y. This is not the case when a setter is involved. The corrected code is above.
EDIT This answer was heavily edited following more info from the OP.
To query the title of currently selected item in NSPopUpButton:
NSMenuItem* selectedItem = [typePopUp selectedItem];
NSString* selectedItemTitle = [selectedItem title];
if ([selectedItemTitle isEqualTo: ... ]) { ... }
Note that comparing UI strings is a very bad idea. A slightest change in UI will immediately break your code, and you are preventing future localization. You should assign numeric or object values to each item using -[NSMenuItem setTag:] or -[NSMenuItem setRepresentedObject:] and use them to identify items instead.

NSMenuItem toggle Bold Font style

I have to implement NSMenuItem such a way that selected NSMenuItem should have Bold Text , this is what i have done,
#implementation NSMenuItem (Font)
-(void)setBoldStyle:(bool)bBold{
NSString* title = [self title] ;
NSFont *pFont = (bold)?[NSFont boldSystemFontOfSize:14]:[NSFont menuFontOfSize:12];
NSDictionary* fontAttribute = [NSDictionary dictionaryWithObjectsAndKeys:
pFont, NSFontAttributeName,
nil] ;
NSMutableAttributedString* newTitle = [[NSMutableAttributedString alloc] initWithString:title
attributes:fontAttribute] ;
[self setAttributedTitle:newTitle] ;
[newTitle release] ;
}
#end
With Above peiece of code, i am able to set the bold text when a particular NSMenuItem gets selected,
but if it needs to be toggled ( Means if an item was bold earlier, it should be normal now), then its not happening,
This is the way i am calling it,
// have we selected any menuitem yet
if ( prevStatusIndex >0){
// then deselect it
pTempMenuItem = [pMenu itemAtIndex:prevStatusIndex];
[pTempMenuItem setBoldStyle:NO];
}
prevStatusIndex = clientStatus+1;
pTempMenuItem = [pMenu itemAtIndex:prevStatusIndex]; // 1 because a separator added
[pTempMenuItem setBoldStyle:YES];
Any idea whats going wrong ?
You need to use similar to this :
if ([pTempMenuItem boldStyle]) {
NSLog(#"currently bold. change it");
[pTempMenuItem setBoldStyle:NO]);
}
else{
[pTempMenuItem setBoldStyle:YES]);
NSLog(#"currenlty normal. change it");
}
We can only guess as there is a lot of information missing from your question - where are prevStatusIndex, pMenuItem, pMenu and clientStatus declared and given values? What is the valid range of clientStatus? Etc.
In the comments you've said you have used the debugger and breakpoints, but gave no indication of what values you saw.
You really need to provide more detail so folk can help you.
Provided the selected index is never 0 (i.e. prevStatusIndex is not 0 or clientStatus is not -1) and pMenu points to the correct menu then your code works. If the selected index can be zero then you need to change your test for de-bolding to prevStatusIndex >= 0 otherwise the first entry in the menu can be bolded but not unbolded.
HTH.

Objective C: Why is Button moving?

I've got a rather strange bug in my app. Whenever I press the second Button that makes the Method go into the "if", one of my Buttons moves a bit to the left.
It looks like this: http://img823.imageshack.us/img823/3686/30000000.jpg
My App:
I've got 12 buttons in a row with Letters on them. Every button has a label above it.
The labels are called Label0, Label1, Label 2,...
There is a word in the String myString. If the button pressed has the first letter of the word on it -> write it in the first label -> look at second letter of the word...
/// Global ///
start = 4;
letterCount = start;
currentChar = [NSString stringWithFormat:#"%c",[myString characterAtIndex:0]];
- (IBAction)pushButton:(id)sender {
UILabel *label = [self valueForKey:[NSString stringWithFormat:#"Label%i" , letterCount]];
if ([[sender currentTitle] isEqualToString:currentChar]) {
label.text = currentChar;
label.hidden = NO;
if (letterCount-start < [myString length]-1) {
letterCount++;
}
currentChar = [NSString stringWithFormat:#"%c",[myString characterAtIndex:letterCount-start]];
}
Nothing in that code seams to fool around with the position of the buttons. Nevertheless its moving... every time...
I'm using xCode 4.6.1
Thanks,
Michael
Try removing that button and adding a new one (giving the new button the same name as the old one) and re-attach all of your IB stuff and see if that fixes it.

Getting button names to string format

I have a lot of custom buttons in my program and I need to use methods to get their names. I've figured out how to get their names through their tag, but I cant seem to follow it through to have the name in a string format.
Heres what I'm using:
-(void)pickRandomToHide {
for (int check = 1; check <=5; check++)
{
int eventNumber = 1 + arc4random() % 43;
UIButton *pick;
pick = (UIButton *)[_mapImageView viewWithTag:eventNumber];
[pick setHidden:YES];
NSString *buttonName;
buttonName = [pick currentTitle];
NSLog(#"%#",buttonName);
}
}
The NSLog just gives 'Null' five times. But 5 buttons are disappearing so the start is working.
The reason you're not seeing any titles is because the buttons are hidden and disabled, whereas the titles are likely only set to appear when the button's control state is "normal" (enabled and visible). Here's more information from Apple on the UIButton control states.
Try doing this:
-(void)pickRandomToHide {
for (int check = 1; check <=5; check++)
{
int eventNumber = 1 + arc4random() % 43;
UIButton *pick = (UIButton *)[_mapImageView viewWithTag:eventNumber];
if(pick)
{
[pick setHidden:YES];
NSString *buttonName = [pick titleForState: UIControlStateNormal];
NSLog(#"%#",buttonName);
} else {
NSLog( #"hmmm, no button with a tag corresponding to event number %d", eventNumber);
}
}
}

Moving the cursor in an UITextView

I try to move the cursor when a UITextView is selected(touched) to simulate kind of a UITextField placeholder thing.
I'd like the cursor to be at the beginning of the first line. My problem is, that [someTextField setSelectedRange]is not working reliably. When I call it in textView:shouldChangeTextInRange:replacementText: it works as it should. But this method is only called when the user starts typing. I'm using textViewDidBeginEditing: to move the cursor when the UITextView becomes the first responder:
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if (textView == self.descriptionText) {
CustomTextView* customTV = (CustomTextView *)textView;
if ([customTV.text isEqualToString:customTV.placeholder]) {
// text in text view is still the placeholder -> move cursor to the beginning
customTV.text = customTV.placeholder;
customTV.textColor = [UIColor lightGrayColor];
customTV.selectedRange = NSMakeRange(0, 0);
}
}
}
Any ideas why customTV.selectedRange = NSMakeRange(0, 0); isn't working correctly in textViewDidBeginEditing: ?
Thanks for your help!
Actually there's a very simple way of accomplishing this.
// Count the characters on screen
NSMutableString *numOfChar = [self.myTextField.text mutableCopy];
// Skip that many characters to the left
self.myTextField.selectedRange = NSMakeRange(self.myTextField.selectedRange.location-[numOfChar length], 0);
Hope this helps.