Assign string to UIButton's tag value - iphone

I wanted to give a string value to UIButton tag for unique identities.
I tried this code.But it doesnt work.
NSString *A;
NSString *B;
NSString *C;
NSString *D;
firstOptionABtn.tag=[A integerValue];
secondOptonBbtn.tag=[B integerValue];
thirdOptionCbtn.tag=[C integerValue];
fourthOptionDbtn.tag=[D integerValue];
- (IBAction)BtnClicked:(UIButton *)sender {
NSLog(#"%ld",(long)sender.tag);
}
I don't like this way but it will print 0 every time. Where am I going wrong?
Please help. Thanks

It returns zero as you did not initialize string, and it has null value when you convert it into integer it returns you zero. And it seems that you create your button from NIB so you can set their tag value from there and then get there value by implementing.
-( IBAction )buttonClicked:(id)sender
{
UIButton *btn= (UIButton *)sender;
NSLog(#"%d",btn.tag);
}
but if u want the output A,B,C, D then there is also a way
-(void)viewDidLoad{
btn1.accessibilityLabel=#"A";
btn2.accessibilityLabel=#"B";
btn3.accessibilityLabel=#"C";
btn4.accessibilityLabel=#"D";
}
-(IBAction)buttonClicked:(id)sender {
UIButton *btn= (UIButton *)sender;
NSLog(#"%#",btn.accessibilityLabel);
}
output is A, B, C, D

What need to use string for set tag value of button... why not set tag of Button statically simply set like :-
firstOptionABtn.tag=1;
First time seen this setting tag with string to int convert
In your queston First is you are not seting the value of you string
NSString *A;
NSString * B;
NSString * C;
NSString * D;
if you set value of string like
A=#"2"
then your code working and you got the value at the button click event
firstOptionABtn.tag=[A integerValue];
its output is
sender tag 2
Into you String value consider any Number value then the covert string to Intiger cosider only Number not alphabet character like
for example
If you set value of string like A=#"2aaabbb" then the output of button tag is 2 But if you set string value like A=#"bb2aaabbb" then output of button tag is Always 0 consider.
UPDATE
if you wish to set character to int
you can convert NSString to ASCII Like Bellow
A=#"A"
int ASCIINumber = [A characterAtIndex:0];
button.tag=ASCIINumber;
OUTPUT IS:- 65 for Upper case if lower case OUTPUT IS 97
But as using above method i suggest to you use simply set tag=intNumber instead of doing above.

It's not possible dear to set string in tag. Tag only takes int value as you said you know.

Create a custom view which is composed of UIButton and a NSString property or an ivar which will serve as tag.
#interface MyButton: UIView
#property(nonatomic, strong) UIButton *button;
#property(nonatomic, strong) NSString *uniqueTag;
#end
Hope that helps!

we can make a category for tag string in UIButton.
#interface UIButton (setTag)
#property(nonatomic, retain) NSString *tagString;
#end
And any where in your file you can set the tag string to your UIButton.
e.g
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTagString:#"Hello"];

you can always create a custom class containing a string property to go along with said classes
for example : create a custom class for UIButton
and then at the Header File put :
#property (nonatomic, strong)NSString *labelTag;
- (id)initWithFrame:(CGRect)frame withLabelTag:(NSString *)str;
and then, at the implementation create a super method of init with frame so it looked like this :
- (id)initWithFrame:(CGRect)frame withLabelTag:(NSString *)str{
self = [super initWithFrame:frame];
if (self) {
//Init code
_labelTag = str;
}
return self;
}
after that, whenever you want to set or call the string tag of the button you only need to declare it and call it like this :
MyCustomButton *button = [[MyCustomButton alloc]initWithFrame:frame withLabelTag:#"this is the title"];
//and to call it :
NSLog (#"the button's tag is :%#", button.labelTag)
or, you could always just use the button's title property and if you don't want it to show on your button, just set its HIDDEN prop to YES

There are two scenarios.
Case 1: If your tag string contains only numbers - (Eg: tagStringValue = "1433")
Use myButton.tag = [tagStringValue intValue];
Get back the button using
UIButton *myButton = ([[self.view viewWithTag:[tagStringValue intValue]] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:[tagStringValue intValue]]:nil;
Case 2: If your tag string contains numbers and strings - (Eg: tagStringValue = "ss1433kk")
Subclass the UIButton and add a property like:
#property (nonatomic, strong) NSString *stringTag; and use this instead of default Tag.

Related

Linking stepper to Slider UIObject in C4

I am very new to C4 so please be gentle...
If I want to link a slider value to a label this is done with NSString stringWithFormat... e.g.:
self.mylabel.text = [NSString stringWithFormat:#"%4.2f",slider.value];
I added a stepper object as well, and now it also updates mylabel:
self.mylabel.text = [NSString stringWithFormat:#"%4.2f",stepper.value];
But it would be intuitive if the slider position follows the label value when I'm using the stepper. but .value is not an available property in UILabel... so how do I take the mylabel.text property and push that into the slider.value property without getting a datatype mismatch error?
This question has 2 answers, how to do it using C4 objects and how to do it with Interface Builder / UIControls. I'll show both ways, UI first so that I can compare the C4 way afterwards.
UIControl
To do this with UIControls first set up your C4WorkSpace.h header so that it has the following methods and properties:
#property (assign, nonatomic) IBOutlet UILabel *myLabel;
#property (assign, nonatomic) IBOutlet UISlider *mySlider;
#property (assign, nonatomic) IBOutlet UIStepper *myStepper;
-(IBAction)sliderWasUpdated:(UISlider *)slider;
-(IBAction)stepperWasUpdated:(UIStepper *)stepper;
Then, in your drag all three components onto your projects XIB file (i.e. a UISlider, UILabel and UIStepper). Link the action sliderWasUpdated: to the slider using the valueChanged option, and the stepperWasUpdated: action to the stepper also using the valueChanged option. You do this step by selecting C4Canvas.xib from your project then right-clicking on the yellow cube, then dragging from the actions listed in the pop-up menu to each of the objects that you recently placed on the canvas.
Next, add the following code to your C4WorkSpace.m file:
#implementation C4WorkSpace
-(void)setup {
self.myStepper.minimumValue = 0.0f;
self.myStepper.maximumValue = 10.0f;
self.mySlider.minimumValue = 0.0f;
self.mySlider.maximumValue = 10.0f;
}
-(IBAction)sliderWasUpdated:(UISlider *)slider {
slider.value = [C4Math round:slider.value];
self.myLabel.text = [NSString stringWithFormat:#"%4.2f",slider.value];
self.myStepper.value = slider.value;
[self.myLabel sizeToFit];
}
-(IBAction)stepperWasUpdated:(UIStepper *)stepper {
self.myLabel.text = [NSString stringWithFormat:#"%4.2f",stepper.value];
self.mySlider.value = stepper.value;
[self.myLabel sizeToFit];
}
#end
In the setup we make sure that the min/max values of both UI objects are the same (so that we can keep them matched up).
In the stepperWasChanged: method we do two things:
We use the stepper's value to set the label's text
We also use the stepper's value to set the slider's value!
In the sliderWasChanged: method we do the same thing, updating the stepper, but we also round the value of the slider so that it increments in steps (just to keep things tidy).
C4Control
To do the same with C4 objects, instead of native UI objects, we set things up a little differently. First, we don't add anything to our C4Canvas.xib, instead we'll set the objects up manually.
In your C4WorkSpace.h file, add the following lines of code:
#property (readwrite, nonatomic, strong) C4Label *myLabel;
#property (readwrite, nonatomic, strong) C4Slider *mySlider;
#property (readwrite, nonatomic, strong) C4Stepper *myStepper;
-(void)sliderWasUpdated:(C4Slider *)slider;
-(void)stepperWasUpdated:(C4Stepper *)stepper;
Notice that most of this is the same except we're using C4 instead of UI prefixes. Also, we call our methods -(void) instead of -(IBAction) because we're not using Interface Builder.
Next, add the following code to your C4WorkSpace.m:
#implementation C4WorkSpace
-(void)setup {
[self createAddObjects];
//calibrate the min/max values
self.myStepper.minimumValue = 0.0f;
self.myStepper.maximumValue = 10.0f;
self.mySlider.minimumValue = 0.0f;
self.mySlider.maximumValue = 10.0f;
}
-(void)sliderWasUpdated:(C4Slider *)slider {
slider.value = [C4Math round:slider.value];
self.myLabel.text = [NSString stringWithFormat:#"%4.2f",slider.value];
self.myStepper.value = slider.value;
[self.myLabel sizeToFit];
}
-(void)stepperWasUpdated:(C4Stepper *)stepper {
self.myLabel.text = [NSString stringWithFormat:#"%4.2f",stepper.value];
self.mySlider.value = stepper.value;
[self.myLabel sizeToFit];
}
-(void)createAddObjects {
//set up the objects
self.myLabel = [C4Label labelWithText:#"values"];
self.myStepper = [C4Stepper stepper];
self.mySlider = [C4Slider slider:CGRectMake(0, 0, 192, 44)];
//position them
CGPoint centerPoint = CGPointMake(self.canvas.center.x,
self.canvas.center.y - 100);
self.myStepper.center = centerPoint;
centerPoint.y += 100;
self.myLabel.center = self.canvas.center;
centerPoint.y += 100;
self.mySlider.center = centerPoint;
//set up action bindings
[self.mySlider runMethod:#"sliderWasUpdated:"
target:self
forEvent:VALUECHANGED];
[self.myStepper runMethod:#"stepperWasUpdated:"
target:self
forEvent:VALUECHANGED];
[self.canvas addObjects:#[self.myStepper,self.myLabel,self.mySlider]];
}
#end
DIFFERENCES
The major difference between the two approaches is whether or not you use Interface Builder. In the C4 approach we need to add a method called createAddObjects to our project so that our slider, label and stepper all get added to the canvas.
This method also contains the methods for binding the actions of our C4UIElements to our code, which happens in the lines:
[self.mySlider runMethod:#"sliderWasUpdated:"
target:self
forEvent:VALUECHANGED];
[self.myStepper runMethod:#"stepperWasUpdated:"
target:self
forEvent:VALUECHANGED];
Once these are set up the only difference is specifying the use of C4 objects instead of UI objects, like:
-(void)sliderWasUpdated:(C4Slider *)slider {...}
instead of
-(IBAction)sliderWasUpdated:(UISlider *)slider {...}

How can I read UITextField value in an IBAction. I'm creating UITextField programmatically

How can I read UITextField value in an IBAction? I'm creating UITextField programmatically. So I can't set #property and #synthesize using Xcode. The code to generate UITextField is as follows:
for(i=0; i<[fieldName count]; i++)
{
UITextField *name = [fieldName objectAtIndex:i];
frame = CGRectMake(fromLeft, fromTop, totalWidth, totalHeight);
name = [[[UITextField alloc] initWithFrame:frame] autorelease];
name.borderStyle = UITextBorderStyleRoundedRect;
name.returnKeyType = UIReturnKeyDone;
//name.placeholder = [fieldName objectAtIndex:i];
name.autocapitalizationType = UITextAutocapitalizationTypeWords;
name.adjustsFontSizeToFitWidth = TRUE;
name.keyboardType = UIKeyboardTypeDefault;
[name addTarget:self action:#selector(doneEditing:) forControlEvents:UIControlEventEditingDidEndOnExit];
[scroller addSubview:name];
fromTop = fromTop + 40;
}
Now I want to read values of each textbox in a button click (IBAction). Can anyone help me please?
You could use something like this to loop through all UITextFields that are subviews of self.view and add their text to a NSMutableArray:
for (UITextField *field in self.view.subviews) {
if ([field isKindOfClass:[UITextField class]]) {
if ([[field text] length] > 0) {
[someMutableArray addObject:field.text];
}
}
}
if your doneEditing: looks like this doneEditing:(id)sender then you can say:
UITextField *field = (UITextField *)sender;
NSString *myText = field.text;
EDIT:
To access a UITextField without setting as an instance variable you need to tag it when you create it:
[textField setTag:1];
then whenever you want to access it you can get it from its parent view by the tag:
UITextField *myTextField = [scroller viewWithTag:1];
NSString *myString = myTextField.text;
in your case, set the tag to i+1 for example to have all the textfield with unique tags.
implement the IBAction function like the following:
-(IBAction) doneEditing:(UITextField*)sender
{
NSString * val = sender.text;
}
try using the UITextFieldDelegate , i think its better for your case.
add each UITextField a Tag and by that you will recognise the UITextField.
NSString *value = sender.text;
If inside an IBAction, of course.
Which ignores that there is a set of text fields, and a single button action.
The simplest solution to the overall problem would be to store a set (or array) of text fields in an instance variable, and iterate over that set in the button action. But that is a rather coarse approach; it is probably better to use the text field delegate method and store text values directly in an array, using the button to trigger the save.
In addition, Apple HIG would tell you that you should update your data model as the text fields are edited, rather than use a "Save" button - which is poor UX design - unless, of course, the values of individual fields can interact.

how to get the value of two sliders during sliding?

I have two sliders in my view and I want to get both value when I slide each one .
but whenever I try to do this the value of the other slider which is not sliding becomes zero and literally I get only one value.
this is what I have done
create two IBAction for each slider
create two property for each slider
#property (retain , nonatomic ) IBOutlet UISlider * slider2;
-(IBAction) slidingN : (id) sender
{
UISlider * si = (UISlider *) sender;
int value = (int) si.value;
NSString * newText = [[NSString alloc] initWithFormat:#"%i" , value];
myLable.text = newText;
int valueD = (int)slider2.value;
[self callSubView:value :valueD];
}
but the value is 0 how can I have both values?
Problem Solved (surpassingly) after restarting Xcode

Iphone-MultiButton-Events

I Have One Xib File
IN Which There Are About 50 Buttons..
And All Are Have Same Functionality...
Like
On Click I Change Background Image (Select)And...
And Second Time Click Also Change Background Packet (Deselect)
..
If I Make All Button Own Events .. Then It's Ok..
But I Want To Create Single Function Which Handles All Buttons...
I Try It.. I Can't Get Specific Typecasting
Coding
.h File
-(IBAction) BtnShpPress:(id)sender;
.m File
-(IBAction) BtnShpPress:(id)sender
{
UIButton *BtnShp= (UIButton * ) sender;
NSString *Str = BtnShp.name; //Here I Ca't Get Specific Object
}
And I Apply This Event On 4 Buttons - TouchDown Events
-(IBAction) BtnShpPress:(id)sender
{
UIButton *BtnShp= (UIButton * ) sender;
NSString *Str = [BtnShp currentTitle]; //This gives title of button
}
You can also set tag and access them too using button.tag
use this to get title -
NSString *Str = [[BtnShp titleLabel] text];

Value of an integer variable in one view always showing 0(ZERO) in another view

I want to access tag value of a button of a view to another view but it always shows zero.
I declare an integer variable: NSInteger tag; in interface part of songView.h and set its #property(nonatomic) NSInteger tag;
In songView.m synthesize it as #synthesize tag;
Now I assign it the tag value of button like this:
-(IBAction)track1ButtonPressed:(id) sender
{
self.tag = [sender tag];
}
Now I want to access this(tag) value in another view i.e. audioView, I code like this in audioView.m:
songView *songview=[songView alloc];
if (songview.tag==1)
{}
else{}
By running this code always else part execute because the value of songview.tag is 0(ZERO),
I also set the tag value of button as 1 in IB.
Try to declare integer variable with different name other than tag..ex: NSInteger btnTag;
Because in general for any view the tag is zero
First of all, you have to not only to allocate your objects, but also initialize it. So replace
songView *songview=[songView alloc];
with
CGRect songFrame = CGRectMake(0.f, 0.f, 120.f, 120.f);
songView *songview=[[songView alloc] initWithFrame:songFrame];
initWithFrame is the designated initializer for a UIView and I suppose your songView class is a subclass of UIView.
Then I am not sure if assign is the default modifier for #property, to make sure define your tag property as
#property(nonatomic, assign) NSInteger tag;
Then it should work. If not, set a breakpoint into your track1ButtonPressed:(id) sender method to see it is getting called and inspect the sender object manually using the debugger.