Switching UISwitch on/off by pressing on UILabel - ios

I've got this method were it displays UILabels and UISwitches right next to them. I want the UISwitch to be switched on and off by pressing on a label as well. I have tagged the switches but I don't know what to do next.. Any help would much appreciated. Thanks!
while (i < numberOfAnswers) {
UILabel *answerLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, y+spaceBetweenAnswers, 240, 30)];
answerLabel.text = [NSString stringWithFormat:#"%# (%#)", questionBank[randomQuestionNumber][1][i][0],questionBank[randomQuestionNumber][1][i][1]];
answerLabel.font = [UIFont systemFontOfSize:15];
answerLabel.textColor = [UIColor darkGrayColor];
answerLabel.numberOfLines=0;
[answerLabel sizeToFit];
[_answerView addSubview:answerLabel];
answerHeight = answerLabel.frame.size.height + spaceBetweenAnswers;
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
mySwitch.transform = CGAffineTransformMakeScale(0.75, 0.75);
if ([questionBank[randomQuestionNumber][1][i][1] isEqual:#"0"]) {
[mySwitch addTarget:self action:#selector(wrongAnswer:) forControlEvents:UIControlEventValueChanged];
} else {
}
mySwitch.tag = i;
[_answerView addSubview:mySwitch];
}

Use a UIButton instead of a UILabel and set an IBAction on it. You can style the button to look exactly like the label. Your IBAction method should look something like this:
- (void)buttonPressed:(UIButton *)sender
{
//Get the view by tag
UISwitch *mySwitch = (UISwitch *)[self.view viewWithTag:yourTag];
[mySwitch.setOn:![mySwitch isOn]];
}
Edit
As mentioned, since you're building the UIButtons in code, you need to add the target to the button to get the button click. Add the action as such:
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

Add a tap gesture recognizer to each label. When it is tapped, you can get the label from the gesture (view). Now you just need to get the switch to update.
You could add a tag to the label which is 1000 + i, then a simple subtraction will give you the switch tag that you need to find.
You could tag the labels and use the tag as the index into an array or switches (possibly IBOutletCollection).

You can do something like this.
UISwitch* mySwitch = [[UISwitch alloc]init];
[self addSubview:mySwitch];
UIButton* switchLabelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
switchLabelBtn.frame = CGRectMake(0, 0, 80, 40);
[switchLabelBtn addTarget:self action:#selector(switchLabelbtnTapped:) forControlEvents:UIControlEventTouchUpInside];
[switchLabelBtn.layer setValue:mySwitch forKey:#"Switch"];
[self addSubview:switchLabelBtn];
- (void)switchLabelbtnTapped:(UIButton*)sender
{
UISwitch* mySwitch = [sender.layer valueForKey:#"Switch"];
mySwitch.on = ![mySwitch isOn];
}

Related

objective c How to access and change dynamically created button background color in a uiscrollview

As you can see in the screenshot I have created multiple buttons dynamically in a UI scroll view. Every button actually holds a date action upon which specific events to that date loads into table. UI Scroll view is global element in the code which can be accessed by any method in the controller.
What I wanted now is access a button (when someone chooses a date to see events on that date) in that scrollview and change its background color. For your convenience I have added the whole code for date and scrollview. Please also note that data are loading from remote server.
Link to the screenshot is as follows
Please forgive me if you see anything wrong in typing. This is my first question in stack.
luckyDateScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(22, 2, lucky_screen_width-45, 23)];
luckyDateScrollView.showsHorizontalScrollIndicator = NO;
CGFloat paperWidth = 50;
int numberOfPapers = [dateRanges count];
for (int i=0; i<[dateRanges count]; i++) {
//NSLog(#"%d: %#", i, dateRange[i]);
//php like exploding with separator |
NSArray *dateString = [dateRanges[i] componentsSeparatedByString:#"|"];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake( 5+ (paperWidth+4) * i , 0, paperWidth, luckyDateScrollView.bounds.size.height)];
btn.titleLabel.font = [UIFont fontWithName:#"Arial" size:11.0f];
[btn setTitle: [NSString stringWithFormat:#"%#",dateString[0]] forState:UIControlStateNormal];
//dateResendButton
[btn setTag:i];
[btn addTarget:self
action:#selector(byDateFilterButton:)
forControlEvents:UIControlEventTouchUpInside];
if([today isEqualToString:dateString[1]]){
[GlobalMethods makeRoundedView:btn WithColorString:#"#ffffff" BGColorString:#"#004D00"];
}else{
[GlobalMethods makeRoundedView:btn WithColorString:#"#ffffff" BGColorString:GlobalVariables.initGV.BlackColor];
}
//[GlobalMethods makeRoundedView:btn WithColorString:#"#ffffff" BGColorString:#"#FF0000"];
[luckyDateScrollView addSubview:btn];
}
contentSize = CGSizeMake( 10 + (paperWidth+4) * numberOfPapers, luckyDateScrollView.bounds.size.height);
luckyDateScrollView.contentSize = contentSize;
// [GlobalMethods makeRoundedView:aScrollView WithColorString:#"#ffffff" BGColorString:GlobalVariables.initGV.BlackColor];
[dateUIView addSubview:luckyDateScrollView];
luckyDateBtnLeftScroll = [[UIButton alloc] initWithFrame:CGRectMake(5, 2, 20, 23)];
[luckyDateBtnLeftScroll setBackgroundImage:[UIImage imageNamed:#"arrow_g_icon_left"] forState:UIControlStateNormal];
[luckyDateBtnLeftScroll addTarget:self action:#selector(dateSetScrollToLeft:) forControlEvents:UIControlEventTouchUpInside];
[dateUIView addSubview:luckyDateBtnLeftScroll];
luckyDateBtnRightScroll = [[UIButton alloc] initWithFrame:CGRectMake(lucky_screen_width-25, 2, 20, 23)];
[luckyDateBtnRightScroll setBackgroundImage:[UIImage imageNamed:#"arrow_g_icon"] forState:UIControlStateNormal];
[luckyDateBtnRightScroll addTarget:self action:#selector(dateSetScrollToRight:) forControlEvents:UIControlEventTouchUpInside];
[dateUIView addSubview:luckyDateBtnRightScroll];
//ViewCollapse.backgroundColor = [UIColor colorWithCGColor: #"#FFD80D"];
If I understand your question correctly you can simply change the background of your button in the byDateFilterButton: method. It should have a sender parameter which would be the button in question.
If you also need to change the background of the other buttons back to normal, you need to keep a reference to them, probably in an array (or dictionary - if you have many buttons and need fast access).
I modified byDateFilterButton method in a following way. Thanks to this SO post Access all buttons in uiscollview
for (id obj in luckyDateScrollView.subviews) {
NSString *classStr = NSStringFromClass([obj class]);
if ([classStr isEqualToString:#"UIButton"]) {
UIButton *button = (UIButton*)obj; //NSLog(#"buttonn tag %ld",(long)button.tag);
if(sender.tag == button.tag){ // currently selected button
[GlobalMethods makeRoundedView:button WithColorString:#"#ffffff" BGColorString:#"#555454"];
}
else{ // the rest of buttons
[GlobalMethods makeRoundedView:button WithColorString:#"#ffffff" BGColorString:GlobalVariables.initGV.BlackColor];
}
}
}

How to make 3 clickable area on a button in Objective-C

I'm new in objective-C and I've create a project that use a button to change some elements from my view. I would like that depending on what part of the button I click, it displays different elements than previous.
For exemple when I click on the left area from button a red circle appears and when I click in the middle, it's the blue circle that appears and in the right area it's a green circle.
I tried searching on google and stackoverflow but I have trouble understanding how the selector used in this case. Could someone help me?
PS: Sorry for the mistakes, my English is not very good
I help you.
First you need the create the small custom view programmatically or through the xib or storyboard
UIView *viewButton = [[UIView alloc] initWithFrame: CGRectMake ( 100, 100, 300, 300)];
[self.view addSubView:viewButton];
Then Create the 3 buttons inside the viewButton
//First Button
UIButton *buttonLeftRed = [UIButton buttonWithType:UIButtonTypeCustom];
OR
UIButton *buttonLeftRed = [UIButton buttonWithType:UIButtonTypeSystem];
buttonLeftRed.frame = CGRectMake(0, 0, 100, 100);
buttonLeftRed.tag = 1;
[buttonLeftRed setTitle:#"Red" forState:UIControlStateNormal];
[buttonLeftRed addTarget:self
action:#selector(actionPressMeOne:) forControlEvents:UIControlEventTouchUpInside];
[viewButton addSubview:buttonLeftRed];
//Second Button
UIButton *buttonMiddleBlue = [UIButton buttonWithType:UIButtonTypeCustom];
OR
UIButton *buttonMiddleBlue = [UIButton buttonWithType:UIButtonTypeSystem];
buttonMiddleBlue.frame = CGRectMake(100, 0, 100, 100);
buttonMiddleBlue.tag = 2;
[buttonMiddleBlue setTitle:#"Blue" forState:UIControlStateNormal];
[buttonMiddleBlue addTarget:self
action:#selector(actionPressMeSecond:) forControlEvents:UIControlEventTouchUpInside];
[viewButton addSubview:buttonMiddleBlue];
//Third Button
UIButton *buttonRightGreen = [UIButton buttonWithType:UIButtonTypeCustom];
OR
UIButton *buttonRightGreen = [UIButton buttonWithType:UIButtonTypeSystem];
buttonRightGreen.frame = CGRectMake(200, 0, 100, 100);
buttonRightGreen.tag = 3;
[buttonRightGreen setTitle:#"Blue" forState:UIControlStateNormal];
[buttonRightGreen addTarget:self
action:#selector(actionPressMeThird:) forControlEvents:UIControlEventTouchUpInside];
[viewButton addSubview:buttonRightGreen];
If you want to change circle button, you have to import the Quartzcore Framework
#import <QuartzCore/QuartzCore.h>
#pragma mark - UIButton Action Methods
//First
- (void)actionPressMeOne:(UIButton *)sender
{
NSLog(#"Pressed Button Tag is - %#",sender.tag);
UIButton *button = sender;
//Then do whatever you want to do here
//half of the width
button.layer.cornerRadius = button.frame.size.width/2.0f;
button.layer.borderColor=[UIColor redColor].CGColor;
button.layer.borderWidth=2.0f;
button.clipsToBounds = YES;
[button setBackgroundColor:[UIColor redColor]];
}
//Second
- (void)actionPressMeSecond:(UIButton *)sender
{
NSLog(#"Pressed Button Tag is - %#",sender.tag);
UIButton *buttonTwo = sender;
//Then do whatever you want to do here
//half of the width
buttonTwo.layer.cornerRadius = button.frame.size.width/2.0f;
buttonTwo.layer.borderColor=[UIColor blueColor].CGColor;
buttonTwo.layer.borderWidth=2.0f;
buttonTwo.clipsToBounds = YES;
[buttonTwo setBackgroundColor:[UIColor blueColor]];
}
//Third
- (void)actionPressMeThird:(UIButton *)sender
{
NSLog(#"Pressed Button Tag is - %#",sender.tag);
UIButton *buttonThree = sender;
//Then do whatever you want to do here
//half of the width
buttonThree.layer.cornerRadius = button.frame.size.width/2.0f;
buttonThree.layer.borderColor=[UIColor greenColor].CGColor;
buttonThree.layer.borderWidth=2.0f;
buttonThree.clipsToBounds = YES;
[buttonThree setBackgroundColor:[UIColor greenColor]];
}
Thank You:-)

How do i disable the editing of a UITextView based on a UISwitch?

I have a UITextView and i want to disable it's 'editable' property if the state of the UISwitch is set to ON.
myTextView = [[UITextView alloc]initWithFrame:CGRectMake(20, 180, 200, 30)];
myTextView.backgroundColor = [UIColor whiteColor];
myTextView.text = #"This is a textView";
[self.view addSubview:myTextView];
mySwitch = [[UISwitch alloc]initWithFrame:CGRectMake(230, 125, 200, 30)];
[self.view addSubview:mySwitch];
I know that i can check the state of a switch using:
if ([mySwitch isOn]) {
myTextView.editable = NO;
} else {
myTextView.editable = YES;
}
The problem is when i run my project the text is not editable, but when i slide the switch the text cannot be edited (which is obvious with above code). I want to know what do i have to do to change the editable property of the UITextView, if i toggle the switch.
UISwitch is a subclass of the UIControl class, which among other things, provides a target-action-based model for receiving updates about the state of the control.
This means that you can use the -[UIControl addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents] method to have your method called when the switch changes its boolean value:
[yourSwitch addTarget:self action:#selector(switchToggled:) forControlEvents:UIControlEventValueChanged]
You can also do this from Interface Builder, by right-clicking on your UISwitch and assigning its action to the appropriate IBAction method:
- (IBAction) switchToggled:(UISwitch*)switchControl {
yourTextView.editable = switchControl.on;
}
You need to add an IBAction and hook it up to the switch method Value Changed
-(IBAction)toggleSwitch:(UISwitch*)sw {
myTextView.editable = sw.on;
NSLog(#"Value Changed");
}
Edit: Code for doing it programmatically rather than via Interface Builder
myTextView = [[UITextView alloc]initWithFrame:CGRectMake(20, 180, 200, 30)];
myTextView.backgroundColor = [UIColor whiteColor];
myTextView.editable = NO;
myTextView.text = #"This is a textView";
[self.view addSubview:myTextView];
mySwitch = [[UISwitch alloc]initWithFrame:CGRectMake(230, 125, 200, 30)];
mySwitch.on = NO;
[mySwitch addTarget:self action:#selector(toggleSwitch:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:mySwitch];
-(void)toggleSwitch:(UISwitch*)sw {
myTextView.editable = sw.on;
}
You have to create an action for the switch which fires when the switch's state has changed. If you are using storyboard, right-drag from the switch to the code (like to create an outlet) and choose action. Inside that function you check whether your switch is now on or off and according to that you make your TextView editable or not
if ([mySwitch isOn]) {
myTextView.editable = NO;
[myTextView resignFirstResponder];
} else {
myTextView.editable = YES;
[myTextView becomeFirstResponder];
}

Accessing UILabel created on run time

I have created UILabel (lblCount) and UIButton (btnAdd) on a UIButton (Add Item Button)'s action method. The new UILabel and UIButton is added to scrollview. The UILabel (lblCount) shows count of UIButton (btnAdd) tapped. Here, addBtnClickCount is an integer which counts the number of click.
UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake( 50, 100*addBtnClickCount, 25, 25)];
lblCount.text = [NSString stringWithFormat:#"%d",count];
lblCount.tag = addBtnClickCount;
lblCount.textColor = [UIColor whiteColor];
lblCount.textAlignment = NSTextAlignmentCenter;
[self.scrollView addSubview:lblCount];
addBtnClickCount = addBtnClickCount+1;
There will be multiple label (lblCount) and button (btnAdd) when user taps Add Item Button. I want to access particular label for particular add button and display the count.
You have already set tag on your label. Create a mutable array labelArray and add label to it. To access the particular label do following code on add button's action.
-(void)addItem:(UIButton*)button{
UILabel* lblShowCount = [_labelArray objectAtIndex:[button tag]];
lblShowCount.text = [NSString stringWithFormat:#"%d", [lblShowCount.text integerValue]+1];
}
Here i understand that #Hem Poudyal, know's that with help of viewWithTag.he will get output. but don't know how to achieved that. so i am describing over here.
Step 1: Here i am adding UILabel and UIButton to self.view instead of UIScrollView. i hope you can convert it as UIScrollView. here i applied some relation between UILabel tag and UIButton tag. that you can see in below code.
for (int i=0; i<10; i++) {
UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake( 50, (i*50)+((i+1)*5), 100, 50)];
lblCount.text = [NSString stringWithFormat:#"%d",0];
lblCount.tag = [[NSString stringWithFormat:#"%d%d",i,i] integerValue];
lblCount.backgroundColor = [UIColor yellowColor];
lblCount.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:lblCount];
UIButton* btnTemp = [UIButton buttonWithType:UIButtonTypeCustom];
btnTemp.tag = i;
btnTemp.backgroundColor = [UIColor redColor];
[btnTemp addTarget:self action:#selector(btnTempClick:) forControlEvents:UIControlEventTouchUpInside];
btnTemp.frame = CGRectMake( 150, (i*50)+((i+1)*5), 100, 50);
[btnTemp setTitle:[NSString stringWithFormat:#"Button : %d",i] forState:UIControlStateNormal];
[self.view addSubview:btnTemp];
}
Step 2: In UIButton selector method, Do the following things.
-(IBAction)btnTempClick:(id)sender{
UIButton* btnInner = sender;
NSInteger lblTagbaseOnButtonTag = [[NSString stringWithFormat:#"%ld%ld",btnInner.tag,btnInner.tag] integerValue];
UILabel* lblReceived = (UILabel*)[self.view viewWithTag:lblTagbaseOnButtonTag];
lblReceived.text = [NSString stringWithFormat:#"%ld",[lblReceived.text integerValue]+1];
}
And Output is :
You should have an array that you add the labels and buttons too (this could be one array containing a dictionary or custom class or multiple arrays). Now, when a button is tapped you can find where it is in the array and get the corresponding label to update.
The cheat way is to set the tag of the buttons and labels so you can find one from the other using viewWithTag:.
You need to set unique tag value while creating the labels and buttons and by using viewWithTag: you can access the respective ui container.

Create a function that is able to check the title of the button pressed

I have a loop for creating buttons dynamically.
for (int b = 0; b < _currentPlayerTeams.count; b++)
{
HNTeamObject *team = _currentPlayerTeams[b];
CGFloat buttonY = 168 + ((b + 1) * distanceBetweenButtons) - 23;
NSString *buttonTitle = [NSString stringWithFormat:#"%# %#",team.teamName, team.seriesName];
UIButton *button = [[UIButton alloc] init];
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:#"images.png"] forState:UIControlStateNormal];
button.titleLabel.textColor = [UIColor blackColor];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
[button addTarget:self
action:#selector(chooseTeamOne:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle: buttonTitle forState:UIControlStateNormal];
button.titleLabel.text = (#"%#", buttonTitle);
button.frame = CGRectMake(labelAndButtonX, buttonY, 268.0, 46.0);
[self.view addSubview:button];
}
I need to make a function that can act as the selector that for each button that is created and look at the button's title. Since I am making the buttons in the loop they are local and do not appear in another function that I create. Any help would be appreciated. I apologize in advance because I am very new to coding and am not quite up to speed with what is going on. Thanks.
Each button will call the chooseTeamOne: function when it is pressed so I assume you want to get the buttons title in that method.
To do so, use the UIButton's title property:
NSLog(#"%#", button.currentTitle);
This will log the button's current title. What is important to note is that I am referencing "button" which is the instance of the UIButton which called the chooseTeamOne method. I am assuming chooseTeamOne takes a UIButton button as a parameter.
If your method takes an 'id' as a parameter you would need to cast the sent object to a UIButton like this:
- (IBAction)chooseTeamOne:(id)sender {
UIButton *button = (UIButton *)sender;
NSString *buttonTitle = button.currentTitle;
}
Do you need a separate selector to return the title? If not then..
I imagine that your chooseTeamOne function is something along the lines of:
-(IBAction)chooseTeamOne:(id)sender {
...do things...
}
in which case, just add
-(IBAction)chooseTeamOne:(id)sender {
UIButton *button = sender;
NSString *stringThatYouWant = button.titleLabel.text; //get the text on the button
...do things...
}

Resources