Labels properties changing in Xcode - ios

I have written this code to change colour of different labels through different buttons
I am new to app development, just got stuck up in pretty basics:
-(IBAction)ButtonPressed:(id)sender
{
UIButton *btn=sender;
if(btn.tag==1)
{
lbl1.text=#"";
lbl1.backgroundColor=[UIColor redColor];
}
if(btn.tag==2)
{
lbl2.text=#"";
lbl2.backgroundColor=[UIColor greenColor];
}
else if(btn.tag==3)
{
lbl3.text=#"";
lbl3.backgroundColor=[UIColor magentaColor];
}
else if(btn.tag==4)
{
lbl4.text=#"";
lbl4.backgroundColor=[UIColor blueColor];
}
else if(btn.tag==5)
{
lbl5.text=#"";
lbl5.backgroundColor=[UIColor brownColor];
}
}
After writing the code the colour of label one is only getting changed.
I have connected all the elements through storyboard though

Try it like this
-(IBAction)ButtonPressed:(id)sender
{
NSInteger i = [sender tag];
if(i==1)
{
lbl1.text=#"";
lbl1.backgroundColor=[UIColor redColor];
}
if(i==2)
{
lbl2.text=#"";
lbl2.backgroundColor=[UIColor greenColor];
}
else if(i==3)
{
lbl3.text=#"";
lbl3.backgroundColor=[UIColor magentaColor];
}
else if(i==4)
{
lbl4.text=#"";
lbl4.backgroundColor=[UIColor blueColor];
}
else if(i==5)
{
lbl5.text=#"";
lbl5.backgroundColor=[UIColor brownColor];
}
}
Or Simply
-(IBAction)ButtonPressed:(id)sender
{
if([sender tag]==1)
{
lbl1.text=#"";
lbl1.backgroundColor=[UIColor redColor];
}
if([sender tag]==2)
{
lbl2.text=#"";
lbl2.backgroundColor=[UIColor greenColor];
}
else if([sender tag]==3)
{
lbl3.text=#"";
lbl3.backgroundColor=[UIColor magentaColor];
}
else if([sender tag]==4)
{
lbl4.text=#"";
lbl4.backgroundColor=[UIColor blueColor];
}
else if([sender tag]==5)
{
lbl5.text=#"";
lbl5.backgroundColor=[UIColor brownColor];
}
}
Also check the tags of the buttons.

Only replace this line UIButton *btn=sender;
with UIButton *btn = (UIButton *)sender;

Related

Returning UIColor causing crashes

I'm trying to use a method to convert string to UIColor like this:
-(UIColor *)getColorFromString:(NSString *)color {
if ([color isEqual: #"red"]) {
return [UIColor redColor];
}
else {
return [UIColor blackColor];
}
}
Using this crashes my tweak
An example:
self.view.backgroundColor = [self getColorFromString: #"red"]; //crashes
self.view.backgroundColor = [UIColor redColor]; //works
You forgot the # before the string:
self.view.backgroundColor = [self getColorFromString:#"red"];
To compare two string you have to use the isEqualToString function.
-(UIColor *)getColorFromString:(NSString *)color {
if ([color isEqualToString:#"red"]) {
return [UIColor redColor];
}
else {
return [UIColor blackColor];
}
}

Detect Selected State of UIButton iOS

How can I detect the selected state of a uibutton?
I have 7 buttons and I have made them to be able to toggle or select multiple buttons at a time.
I want to be able to tell which buttons are in a selected state when I push the done button.
So if M, T and W are selected then I want to be able to detect that when pushing done.
I currently put a tag on the button and then call a method to unselect or select multiple buttons.
self.repeatOccurrenceFrequencyWeeklyTF = [[UITextField alloc]init];
self.repeatOccurrenceFrequencyWeeklyTF.frame = CGRectMake(80, 80, 32, 32);
self.repeatOccurrenceFrequencyWeeklyTF.delegate = self;
self.repeatOccurrenceFrequencyWeeklyTF.background = [UIImage imageNamed:#"repeatWeekly"];
self.repeatOccurrenceFrequencyWeeklyTF.font = [UIFont fontWithName:#"SegoeWP" size:15];
self.repeatOccurrenceFrequencyWeeklyTF.textColor = [UIColor appGreyText];
[self.repeatOccurrenceFrequencyWeeklyTF setValue:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0] forKeyPath:#"_placeholderLabel.textColor"];
self.repeatOccurrenceFrequencyWeeklyTF.placeholder = #"1";
UIView *leftView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, self.repeatOccurrenceFrequencyWeeklyTF.frame.size.height)];
self.repeatOccurrenceFrequencyWeeklyTF.leftView = leftView1;
self.repeatOccurrenceFrequencyWeeklyTF.leftViewMode = UITextFieldViewModeAlways;
self.repeatOccurrenceFrequencyWeeklyTF.rightViewMode = UITextFieldViewModeAlways;
self.keyboardToolbar = [self createInputToolbar];
self.repeatOccurrenceFrequencyWeeklyTF.inputAccessoryView = self.keyboardToolbar;
self.repeatOccurrenceFrequencyWeeklyTF.delegate = self;
self.repeatOccurrenceFrequencyWeeklyTF.keyboardType = UIKeyboardTypeNumberPad;
self.repeatOccurrenceFrequencyWeeklyTF.enabled = NO;
[self.view addSubview:self.repeatOccurrenceFrequencyWeeklyTF];
// Now, in your button action handler, you can do something like this:
- (void)mondayButtonTouch:(UIButton *)aButton withEvent:(UIEvent *)event
{
aButton.selected = !aButton.selected;
if(aButton.tag == 111) {
}
if(aButton.tag == 222) {
}
if(aButton.tag == 333) {
}
if(aButton.tag == 444) {
}
if(aButton.tag == 555) {
}
if(aButton.tag == 666) {
}
NSLog(#"dsfdfdfsdfs %ld", (long)aButton.tag);
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
}
I would use a NS_ENUM (which helps to keep a nice and readable code) and a NSMutableArray to keep track of your selected buttons.
Declare a enum that looks something like this:
typedef NS_ENUM(NSInteger, Weekday) {
WeekdayMonday,
WeekdayTuesday,
WeekdayWednesday,
WeekdayThursday,
WeekdayFriday,
WeekdaySaturday,
WeekdaySunday
};
Then tag your buttons with the correct enum:
tuesdayButton.tag = WeekdayTuesday;
And check when you tap button if your enum exists in your array:
- (void)buttonTouch:(UIButton *)aButton withEvent:(UIEvent *)event
{
if ([array containsObject:#(aButton.tag)]){ //exists, remove it from array
[array removeObjectIdenticalTo:#(aButton.tag)];
}
}else{
[array addObject:#(aButton.tag)];
}
}
A possibility is to create an NSMutableArray named selectedButton. Do like this:
- (void)mondayButtonTouch:(UIButton *)aButton withEvent:(UIEvent *)event
{
aButton.selected = !aButton.selected;
if(!aButton.selected && selectedButton.containsObject(aButton.Tag)) {
[selectedButton removeObject:aButton.tag];
}
else if(aButton.selected && !selectedButton.containsObject(aButton.Tag)) {
[selectedButton addObject:aButton.tag];
}
// do your stuff here
}
Now on done button click you have all the button thats tags are selected will be trackable with selectedButton array.
You can use:
[self.view viewWithTag:yourTagHere]
you can use this :
for (UIButton *btn in [self.view subviews]) { // self.view (change it with your button superview)
if ([btn isKindOfClass:[UIButton class]] && [btn isSelected] == YES) {
// here you found the button which is selected
}
}
[self.view viewWithTag:yourTagHere] replace

How to set "if there is text in text view"

I have a UIButton that is gray when the user enters a viewController. There is also a UITextView. If the user enters text into the UITextView, then the button should turn red, but if the text view is blank, the the button is gray. If was thinking of doing something like bellow, which does change the color to red if the user enters text, but if the user deletes the text, it stays red instead of going back to gray. Here is the code I am using:
- (void)textViewDidChange:(UITextView *)textView {
if (self.textView.text.length == 0) {
self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:193/255.5 green:193/255.0 blue:193/255.0 alpha:1.0];
}else{
self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
}
if (self.titleView.text.length == 0) {
self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:193/255.5 green:193/255.0 blue:193/255.0 alpha:1.0];
}else{
self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
}
NSLog(#"Typing has stopped");
}
Use if (self.textView.text.length == 0) instead of checking if the text is null.
For Swift 3:
if (self.textView.text.characters.count == 0)
You could bind the button image to the text view value and then use a value transformer to put in different colored images depending on if there's input.
Code is for OSX but hopefully it's adaptable.
#implementation DBHasTextImageTransformer
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
+ (Class)transformedValueClass
{
return [NSImage class];
}
+ (BOOL)allowsReverseTransformation
{
return NO;
}
- (id)transformedValue:(id)value
{
if ((value == NULL) || [value isEqualToString:#""]) {
return [NSImage imageNamed: #"NoTextImage"];
} else {
return [NSImage imageNamed: #"HasTextImage"];
}
}
#end

Get indexPath on UITableView's editing mode

I have a UITableView with CustomCell. Whenever UITableView is in editing mode i have following code in CustomCell.
- (void)willTransitionToState:(UITableViewCellStateMask)state{
[super willTransitionToState:state];
if (state == UITableViewCellStateShowingEditControlMask)
{
self.delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.delBtn setFrame:CGRectMake(10, 15, 25, 25)];
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
buttonCurrentStatus = YES;
[self.delBtn addTarget:self action:#selector(delBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.delBtn];
}
else
{
if(self.delBtn)
{
[self.delBtn removeFromSuperview];
self.delBtn = nil;
}
} }
- (void)delBtnPressed:(id)sender {
if (buttonCurrentStatus == NO)
{
buttonCurrentStatus = YES;
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
}
else
{
buttonCurrentStatus = NO;
[self.delBtn setImage:[UIImage imageNamed:#"selection.png"] forState:UIControlStateNormal];
} }
Now how can i get indexPath from CustomCell of UITableview ?
You can use UITableView indexPathForCell:.
Obviously, for that you'll need a reference to the table inside the cell class. If you want to make it a property of your cell, be sure to make it weak to avoid a reference cycle.
I have found the best way of doing this is to create Delegate/Protocol on cell. Make the delegate the ViewController and pass it in. Then you can call indexPathForCell on the tableview at that point. Example below.
- (void)willTransitionToState:(UITableViewCellStateMask)state{
[super willTransitionToState:state];
if (state == UITableViewCellStateShowingEditControlMask)
{
self.delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.delBtn setFrame:CGRectMake(10, 15, 25, 25)];
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
buttonCurrentStatus = YES;
[self.delBtn addTarget:self action:#selector(delBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.delBtn];
}
else
{
if(self.delBtn)
{
[self.delBtn removeFromSuperview];
self.delBtn = nil;
}
} }
- (void)delBtnPressed:(id)sender {
if (buttonCurrentStatus == NO)
{
buttonCurrentStatus = YES;
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
}
else
{
buttonCurrentStatus = NO;
[self.delBtn setImage:[UIImage imageNamed:#"selection.png"] forState:UIControlStateNormal];
}
if ([self.delegate respondsToSelector:(customCelldelBtnPressed:)]) {
[self.delegate customCelldelBtnPressed:self];
}
}
// of course you will need to actually create the delegate or protocol and implement it on the view controller.

How to move from a View to a Tab Bar Controller in iOS?

I'm very new to iOS and I have an issue.
I have a view with a login form and a button.
I want to make it so that once the button is pressed, the login is processed and if successful it loads the first tab of a Tab Bar Controller.
How do I do this? I've tried creating a manual segue and loading it but that doesn't work :(
Here is my code for what happens after login (Its a GitHub login form):
- (IBAction)login:(id)sender {
Boolean error = NO;
NSString* username = _usernameField.text;
NSString* password = _passwordField.text;
UIColor *red = [UIColor colorWithRed:255/255.0f green:0/255.0f blue:0/255.0f alpha:1.0f];
UIColor *black = [UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:1.0f];
GitHub* github = [[GitHub alloc] init];
bool result = NO;
// Checking for blanks
if([username isEqualToString:#""])
{
[_usernameLabel setTextColor:red];
error = YES;
}
else
{
[_usernameLabel setTextColor:black];
}
if([password isEqualToString:#""])
{
[_passwordLabel setTextColor:red];
error = YES;
}
else
{
[_passwordLabel setTextColor:black];
}
if(!error)
{
result = [github loginWithUsername:username AndPassword:password];
if(result == YES)
{
// Logged in successfully!
[_errorLabel setHidden:YES];
NSLog(#"YEP");
[self performSegueWithIdentifier:#"loginSegue" sender:self];
}
else
{
// Error Handling
[_errorLabel setText:#"Error: Incorrect Username / Password"];
[_errorLabel setHidden:NO];
[_passwordField setText:#""];
}
}
else
{
// Error Handling
[_errorLabel setText:#"Error: Please correct errors below:"];
[_errorLabel setHidden:NO];
[_passwordField setText:#""];
}
}

Resources