Change the background color of a button - ios

I have code that counts upwards when buttons on my app are pressed, but I'd also like to change the button's background color once it has been tapped.
Can I simply add a backgroundColor to the below code?
- (IBAction)buttonPressed {
count++;
totalLabel.text = [NSString stringWithFormat:#"Hours\n%li",(long)count];
}
#end

Sure. The easiest thing to do is change your IBAction so it receives the button that's been tapped.
-(IBAction)buttonPressed:(UIButton*)button {
button.backgroundColor = [UIColor redColor];
}
(You'll need to reconnect the outlet from the nib as well so it knows that the new selector is buttonPressed:, not just buttonPressed.

Related

how would is change background image using UIsegmented control

how would is change background image using UIsegmented control ?
i want to change the background image using segment control and after select that image for above process.
Here's a link to the documentation for UISegmentedControl.
Edit
Maybe I had misunderstood your question. If you want to change the background image of a view, you can add your controller as a target for the segmented control.
[segmentedControl addTarget:self action:#selector(updateBackgroundImage:) forControlEvents:UIControlEventValueChanged];
When the UIControlEventValueChanged gets triggered for your control you can use any of this methods to change the background image you want.
- (void)updateBackgroundImage:(UISegmentedControl *)sender {
self.imageView = [UIImage imageNamed:(sender.selectedSegmentIndex ? #"foo": #"bar")];
}
Original Answer
As you'll find it that document you can change the appearance of the control in different ways. A few examples.
-[UISegmentedControl setBackgroundImage:forState:barMetrics:]
-[UISegmentedControl dividerImageForLeftSegmentState:rightSegmentState:barMetrics:]
-[UISegmentedControl setImage:forSegmentAtIndex:]
When the UIControlEventValueChanged gets triggered for your control you can use any of this methods to change the sender's appearance.
You have to add Target to segmented controller like
Then, when you click on any segment your "action" method will get called , change background image or do anything in "action" method
[segmentedControl addTarget:self action:#selector(action:)forControlEvents:UIControlEventValueChanged];
Method implementation should like
-(void)action:(id)sender
{
//code for setting background image.
}
Set the IBAction to your segmentbar with UIControlEventValueChanged event type and based on selected index you can change the image of your imageView
-(IBAction)segmentedChartButtonChanged:(id)sender
{
switch (self.segmentedButton.selectedSegmentIndex) {
case 0:
self.imageView.image = [UIImage imagenamed:#"imageName"];
break;
case 1:
self.imageView.image = [UIImage imagenamed:#"imageName"];
break;
default:
break;
}
}
Try this one.. May be it will help you..
First take UIImageView and set IBOutlet of that and give name like Backgroundimg And also add Segment value change method And also set outlet to Imageview in xib and outlet of method to UISegmentControl.
//.h file
IBOutlet UIImageView *Backgroundimg;
-(IBAction)SegmentChanged:(id)sender;
And just add below code in .m file
//.m file
-(IBAction)SegmentChanged:(id)sender
{
UISegmentedControl *seg=(UISegmentedControl *)sender;
if(seg.selectedSegmentIndex==0)
{
[Backgroundimg setImage:[UIImage imageNamed:#"intro1.png"]];
}
else if(seg.selectedSegmentIndex==1)
{
[Backgroundimg setImage:[UIImage imageNamed:#"intro2.png"]];
}
}

Action not happening when tapping UIButton

I have a UIButton placed on a UIImageView and UILabel.
When i press down the button i want an image to show in the UIImageView and the text color of the UILabel to be changed, and when i pull up my finger i want the image to disappear and the text color of the UILabel changed back to black.
- (void)highlightActivity:(id)sender {
activityImage.image = [UIImage imageNamed:[[NSMutableString alloc] initWithString:activityName]];
activityLabel.textColor = activityColor;
}
- (void)deHighlightActivity:(id)sender {
activityLabel.textColor = [UIColor blackColor];
activityImage.image = nil;
}
It works fine when i press the button and then release, but i have a problem when tapping the button, the image isn't showing at all and the text color isn't changing.
Any ideas how to make it happen when tapping too?
Thanks,
Naor.
I think the problem is you attach both
Touch Up inside and outside on deHighlightActivity.
Because, when you pressed the button, you will release (touch up) the button eventually, if you put both touch up inside and outside on deHighlightActivity, that action will be called every time. So that your tapping action calls deHighlightActivity as well.
I don't know what exactly you are trying to do here, but looks like you have some conflicts on your design.

Text in a UIButton doesn't appear when set programatically

I have a standard UIButton which I've connected as an outlet to a view controller.
Within the VC if I have this:
self.pulldownButton.hidden = NO;
[self.pulldownButton setTitle:NSLocalizedString(#"Some text", #"some key")
forState:UIControlStateNormal];
Then the button appears but it's empty.
There is no issue in your code. It is fine. I suppose you have added button through IB and you have not connected its outlet. Thats why no change reflects. So connect outlet.
Edit: Other case may be you have set an image in foreground rather then background. So if you have set an image in button in foreground then set it to background.
Hope it helps you.
1 do this to check if the issue is with background:
#import <QuartzCore/QuartzCore.h>
self.pulldownButton.layer.borderColor = [UIColor greenColor] CGColor];
self.pulldownButton.layer.borderWidth = 2;
2 Log to check if the frame and super view are proper:
-(void) viewDidAppear:(BOOL) animated
{
[super viewWillAppear:animated];
NSLog(NSStringFromCGRect(self.pulldownButton.superview.rect));
NSLog(NSStringFromCGRect(self.pulldownButton.rect));
}

How to set the UIButton state to be highlighted after pressing it

I have a typical requirement wherein I need to keep a button in highlighted state after pressing it. I need to perform a task which should work only when a button is in highlighted state. Actually I am setting a button state to highlighted programatically.
[sender setHighlighted:YES];
And once the button is in highlighted state i need to perform another action.
- (IBAction)changeState: (UIButton*)sender
{
if (sender.highlighted == YES)
{
[self performSomeAtion:sender];
}
}
But, to my horror, whenever I press any button, the above condition is becoming true and the action is being performed repeatedly. Is there any way in which i can keep a UIButton's state to be highlighted after pressing it?
EDIT - Actually I need to perform 3 different actions for 3 different states of the button. I am already making use of selected state and normal state. Now, I need to make use of the highlighted state.
[sender setSelected:YES];
or you can simulate this effect with two image for your UIButton (notselectedimage.png and selectedimage.png), then keep track button state with a BOOL variable like BOOL buttonCurrentStatus;. Then in .h file:
BOOL buttonCurrentStatus;
and in .m file
// connect this method with Touchupinside function
- (IBAction)changeState:(UIButton*)sender
{
/* if we have multiple buttons, then we can
differentiate them by tag value of button.*/
// But note that you have to set the tag value before use this method.
if([sender tag] == yourButtontag){
if (buttonCurrentStatus == NO)
{
buttonCurrentStatus = YES;
[butt setImage: [UIImage imageNamed:#"selectedImage.png"] forState:UIControlStateNormal];
//[self performSomeAction:sender];
}
else
{
buttonCurrentStatus = NO;
[butt setImage:[UIImage imageNamed:#"notSelectedImage.png"] forState:UIControlStateNormal];
//[self performSomeAction:sender];
}
}
}
- (void)mybutton:(id)sender
{
UIButton *button = (UIButton *)sender;
button.selected = ![button isSelected]; // Important line
if (button.selected)
{
NSLog(#"Selected");
NSLog(#"%i",button.tag);
}
else
{
NSLog(#"Un Selected");
NSLog(#"%i",button.tag);
}
}
The highlighted state is used to highlight the button while it is being touched. A touch down event in the button highlights it. You should use the "selected" state instead.
If what you want to do is perform an action after the button is pressed, don't attach your method to the state change event, attach your method to the TouchUpInside event.
I just find a way, so I share it, just in case...
I kept my UIButton and set one image for each state (so you could go up to a 4 states button).
I set the UserInteractionEnabled to NO -> This button won't receive any touch.
The purpose of this first button is to show a state
I create a second custom UIButton with the same frame than the first one. For this one, none image will be set for the state (it's a fully transparent button). The purpose of this button is to catch the touch event. So I added a target to this button on the TouchUpInside event. And then when the event is fired, I change the state of the first button to Disabled, Highlighted, Selected, or none of these state (= Default state).
Everything is working like a charm!
The way you describe it, you'd be better off subclassing UIView to create your own three-state button.
Actually, you should even implement your own multistate buttonView, and manage the state it's in internally via an array of PNG for the looks and an array of states to know how many times it's been pressed.
Use [sender setSelected: YES];, I think it will be useful to you.
UIButton *btn_tmp=sender;
if(!(btn_tmp.selected))
{
[btn_temp setHighlighted:YES];
}
For iOS 7 only: you should consider setting the image renderMode to UIImageRenderingModeAlwaysTemplate. You can then use the tintColor to represent various states.
see How to apply a tintColor to a UIImage?
and
see Tint a UIView with all its subviews
The solution is tricky but it's possible.
The problem is that you tried to change the highlighted status in the button action method, which I suppose makes a clean up or check process at the end of the action and switch the highlighted status. When you try to debug it you get the highlighted = 1 but it will change at the end.
Strange but your "3 statuses button" is sometimes useful, when you'd like to keep a button in "highlighted" mode like the "selected" mode to get different action depending on the 3 statuses.
The only problem that you couldn't analyze this or switch it to highlighted mode in the button action method as this will switch to highlighted mode immediately as the user push it AND switch it back at the end.
The solution is using a dispatch.
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[theButton setHighlighted:YES];
});
This will do the trick and you could use the 3 statuses.
According to apple, UIButton has a property of imageView:
Although this property is read-only, its own properties are read/write. Use these properties to configure the appearance and behavior of the button’s view
This means that you can set in the IB (in the storyboard) a picture for this button and set the highlighted picture:
Open the Attribute inspector.
Under Button section, choose an image.
In the same section, change the State Config to Highlighted. Notice the image you chose under default is now gone and now you can set a new picture for the Highlighted.
Now you have a button with 2 state config and all you have to do during runtime to change the button.highlighted = true. Also, check the UIControl under Configuring the Control’s Attributes for more states.
You can also do it programatically as follows:
Swift (and almost the same in Objective-C):
// Setting the highlighted image
self.someButton.imageView?.highlightedImage = UIImage(named: "imageNameFromImageAssest")
// someButton will now some the highlighted image and NOT the image set in the IB
self.someButton.imageView?.highlighted = true

Clear button on UITextView

How can I add a clear button (cross inside a circle) for UITextView like UITextField has?
Based on the answer from GhostRider a more accurate and up to date implementation:
int kClearButtonWidth = 15;
int kClearButtonHeight = kClearButtonWidth;
//add the clear button
self.clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.clearButton setImage:[UIImage imageNamed:#"UITextFieldClearButton.png"] forState:UIControlStateNormal];
[self.clearButton setImage:[UIImage imageNamed:#"UITextFieldClearButtonPressed.png"] forState:UIControlStateHighlighted];
self.clearButton.frame = CGRectMake(0, 0, kClearButtonWidth, kClearButtonHeight);
self.clearButton.center = CGPointMake(self.textView.frame.size.width - kClearButtonWidth , kClearButtonHeight);
[self.clearButton addTarget:self action:#selector(clearTextView:) forControlEvents:UIControlEventTouchUpInside];
[self.textView addSubview:self.clearButton];
And the method
- (void)clearTextView:(id)sender{
self.textView.text = #"";
}
You can use this images for the two states of the button:
just make a uibutton and put it on uitextview and set its action for clear text view;
uitextview.frame = (0,0,320,416);
uibutton.frame = (310,0,10,10);
[uibutton setimage:#"cross.png" forcontrolstate:uicontrolstatenoraml];
[uibutton addTarget:self action:#selector(clearButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
-(void)clearButtonSelected{
uitextview=#"";
}
hope you want to clear the text view text when you click on cross button above is help
if not understand then i can send you proper program for that
From product perspective, if you're going to have a clear button, you probably want to use a UITextField instead of a UITextView and UITextField supports a clear button natively - set the clearButtonMode property as such:
UITextField *textfield = ...;
textfield.clearButtonMode = UITextFieldViewModeAlways;
See screenshot:
You could use UITextFieldViewModeWhileEditing to only present the clear button while the user is actively updating the content.
There's nothing built in like there is for the UITextField. You'd have to add the view yourself (probably a UIButton) and place it correctly and also somehow get the text to wrap around it correctly. (And I don't think the latter is really possible.)
Maybe instead you should display a toolbar above the keyboard (or an inputAccessoryView if you're targeting 3.2 and later) that provides a clear button.
For me changing the .frame or the .contentInset properties did not work.
For me the best result came from:
1) adding a UIView to the controller, give it round corners and a border to mimic a UITextView.
self.viewTextBackground.layer.borderColor = [UIColor colorWithRed:171/255.0 green:171/255.0 blue:171/255.0 alpha:1.0].CGColor;
self.viewTextBackground.layer.borderWidth = 1.0f;
self.viewTextBackground.layer.cornerRadius = 9.0f;
2) place UITextView on top of this UIView. Place it so that the borders of the underlying UIView stay visible.
3) give the UITextView round corners:
self.textNote.layer.cornerRadius = 9.0f;
3) Make its width fe. 30pixels less compared to the underlying UIView. You now have space for a clear-button.
4) simply add a UIButton to your controller and place it in the top-right corner of the underlying UIView.
5) change the buttons properties: set its type to 'custom' and set its image to the image of a grey cross.
6) bind an action to the button te clear the UITextView
You can add a clear button like the one in the attached screenshot with minimal coding. Just follow these steps:
Select the storyboard and drag a UIButton into your UITextView
Set the buttons constraints
Assign a title or a background image
Create the button's IBOutlet reference and the action (see onClearPressed(_:) below) for "Touch Up Inside" in the ViewController
Implement the textViewDidChange(_:) UITextViewDelegate delegate method, and make sure to set the button's isEnabled property based on the textfield content, e.g.:
func textViewDidChange(_ textView: UITextView) {
clearButton.isEnabled = !textView.text.isEmpty
}
Implement the onClearPressed(_:) action:
#IBAction func onClearPressed(_ sender: Any) {
textView.text = ""
clearButton.isEnabled = false
}
That's it.

Resources