iOS edit UIButton properties - objective-c

I am working on the basics of iOS development.
So far I have a button that on press, will show some text. But what I want to do is after it is pressed, I want it to then change the text of the button, so far this is what I have:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//button.backgroundColor = [UIColor redColor];
button.titleLabel.textColor=[UIColor blackColor];
button.frame = CGRectMake(25, 100, 275, 60);
[button setTitle:#"Press this button to reveal the text!" forState:UIControlStateNormal];
[button addTarget:self action:#selector(button_method:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)button_method:(UIButton *)sender {
NSString *test = #"I am learning Objective-C for the very first time! Also, this is my first ever variable!";
// handle button press
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 25, 275, 60)];
label.text = test;
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
//label.lineBreakMode = NSLineBreakByWordWrapping; //iOS 6 only
[self.view addSubview:label];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
When I try adding [button setTitle:#"You pressed the button"]; to button_method
This doesn't work... why? And how would I make it work?

When I try adding [button setTitle:#"You pressed the button"]; to button_method, it doesn't work... why?
Because that method is nonexistent on UIButton.
And how would I make it work?
By using a method that UIButton actually responds to. For example:
[sender setTitle:#"You pressed the button" forState:UIControlStateNormal];
And read the relevant documentation, please.

Your code will not change the title of the button. But simply add a label as a subview for your view. Is this what you want?
If you want to change the text on the button you will want to do sender.title.text = test; in your button_method
I also recommend adding a NSLog(#"Button pressed"); to your button press method to double check that it is being called.

Related

Button click not registering

I have an Xcode 5 button problem.
I create a number of button programatically on a UIViewController and then want to register clicks on these buttons. I use NSLog to track the clicks but it seems that no clicks are registered in the log.
Can anyone help please?
The ultimate aim to to segue to next UIViewController on each button click, but was just testing to see if button clicks were registered first.
Here is how I create the buttons in viewDidLoad (only 1 shown).
NOTE: the if-statement used only to check which buttons were pressed in previous view.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *myString = [NSString stringWithFormat:#"%d", self.tagNumber ];
if (self.tagNumber == 1)
{
hotelButton = [UIButton buttonWithType:UIButtonTypeCustom];
hotelButton.tag = 1;
hotelButton.frame = CGRectMake(60, 60, 300.f, 100.f);
UIImage *buttonImage1 = [UIImage imageNamed:#"buttonImage1.png"];
[hotelButton setBackgroundImage:buttonImage1 forState:UIControlStateNormal];
[self.view addSubview:hotelButton];
// Add targets and actions
[hotelButton addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside];
}
}
And here is how I check for button clicks
- (void) buttonClicked
{
NSLog(#"Button %i clicked", hotelButton.tag);
}
NOTE: I also tried the following:
- (void) buttonClicked:(UIButton *) button
{
NSLog(#"Button %ld clicked", (long int)[button tag]);
}
But that gave an error "undeclared selector buttonClicked" in my viewDidLoad pointing to action#selector):
[hotelButton addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside];
Use this:
[hotelButton addTarget:self action:#selector(buttonClicked)
forControlEvents:UIControlEventTouchUpInside];
From Apple Docs:
UIControlEventTouchUpInside
A touch-up event in the control where the finger is inside the bounds of the control.
UIControlEventTouchUpOutside
A touch-up event in the control where the finger is outside the bounds of the control
And keep this method:
- (void) buttonClicked
{
NSLog(#"Button %i clicked", hotelButton.tag);
}
try and change outside to inside,
[hotelButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
Try this,
[hotelButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
and pass the sender,
- (void) buttonClicked:(UIButton*)sender
{
NSLog(#"Button %i clicked", [sender tag]);
}
Have modified your if condition. Please follow :-
if (self.tagNumber == 1)
{
hotelButton = [UIButton buttonWithType:UIButtonTypeCustom];
hotelButton.tag = 1;
hotelButton.frame = CGRectMake(60, 60, 300.f, 100.f);
UIImage *buttonImage1 = [UIImage imageNamed:#"buttonImage1.png"];
[hotelButton setBackgroundImage:buttonImage1 forState:UIControlStateNormal];
hotelButton.showsTouchWhenHighlighted = YES;
hotelButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
[hotelButton addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:hotelButton];
}

How to hide button after the button is manual added in Cocoa Touch?

I have added button manually in for loop, after that, how to hide or change the button and hide label?
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 170, 150.0, 30.0);
[button setTitle:#"My Button" forState:UIControlStateNormal];
[button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UILabel *lblFileName = [[UILabel alloc] init];
lblFileName.text = [[objectArray objectAtIndex:i] valueForKey:#"fileName"];
lblFileName.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:lblFileName];
-(IBAction)myAction:(id)sender
{
// hide the button or change title button and hide label
}
If u are adding buttons & labels in for loop, then try following solution.
button.tag = i + 1;//0 is default tag for all views.
lblFileName.tag = i + 1;
-(IBAction)myAction:(id)sender
{
UIButton *btn= (UIButton *)sender;
[btn setHidden:YES];// hide the button
btn.titleLabel.text = [[objectArray objectAtIndex:[sender tag]] valueForKey:#"fileName"];
//Get the label of selected button using button tag.
[[self.view viewWithTag:[sender tag]] setHidden:YES];
}
-(IBAction)myAction:(id)sender
{
// hide the button or change title button
[button setHidden:YES];
}
In myAction:(id)sender sender is your Button.
- (IBAction)myAction:(id)sender {
[sender setHidden:YES];
}
But in this case you cannot make the button visible anymore, because you have no reference to it. I think it would be better to create a property for the button.
-(IBAction)btn:(id)sender
{
btn.hidden=YES;
}
try this.
Other answerers have already shown how sender is the button you want, butif you want to access the button in an different method (for example, if you want to make it visible again) you will need to create a property on the object that created the button.
To do so, put this in your class #interface:
#property (strong) UIButton *myButton;
And #synthesize it in your #implementation:
#implementation WhateverClass
#synthesize myButton = _myButton;
Then you can set the property to your custom button:
self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.myButton.frame = CGRectMake(80.0, 170, 150.0, 30.0);
[self.myButton setTitle:#"My Button" forState:UIControlStateNormal];
[self.myButton addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.myButton];
and access it anywhere (after it has been created) like so:
-(IBAction)myAction:(id)sender
{
[self.myButton setTitle:#"Pressed!" forState:UIControlStateNormal];
[self.myButton setHidden:YES];
}
Give unique tag for each button and label like Girish said.No two tags should not be same.
Consider you have 10 button and 10 label. Then give tag for button 1 to 10 and label 11 to 20.
Then on your method you can access any label or button using corresponding tag.
UIButton *button=(UIButton *)[self.view viewWithTag:1];
UILabel *label=(UILabel *)[self.view viewWithTag:11];

Why is my UIButton not displaying on my view?

I have a iOS5 project using storyboard and with ARC on.
I have a view in storyboard with the class thisViewController and in there I got a smaller subview which I dragged in and gave it the class thisView.
thisView has a custom drawRect function, that works and draws what I want nicely.
But I also want to add buttons dynamically, so I'll add them in the initWithFrame method of thisView like so:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(#"This is called <3");
UIButton *btn= [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 50, 50);
btn.backgroundColor = [UIColor redColor];
[btn setTitle:#"Play" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
[self bringSubviewToFront:btn]; // last thing I tried, didn't work, thought z-index was to low or something
}
return self;
}
The function is being called since the NSLog displays, but the button is nowhere to be found
--EDIT--
Extra information:
ThisView.h
#interface RadarView : UIView <CLLocationManagerDelegate>{
CLLocation *currentLocation;
}
Dont add the SubView in the init method.
Add the SubView in the - (void)layoutSubviews.
- (void)layoutSubviews {
[super layoutSubviews];
if (![self viewWithTag:12345]) {
UIButton *btn= [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 50, 50);
btn.tag = 12345;
btn.backgroundColor = [UIColor redColor];
[btn setTitle:#"Play" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
}
I found what the problem was thanks to some comments and the chat
There was an init in the radarviewcontroller, which triggered initwithframe, which made the NSLog display, and the initwithcoder wasn't used so I didn't see anything, that was the problem and got stuff mixed up. Thanks for commenting and helpin!

How can I replace the text in a round rect button with a spinner?

I have a view with a generic rounded rect button that segues to another view. When users press the rounded rect it starts a fetch. I would like to have a spinning wheel replace the text ("Next") inside the rounded rect button while the fetch is processed.
I created the spinner:
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner startAnimating];
But I don't know how to make it replace the text in the rounded rect button.
Any suggestion? Thank you.
Create (or get a reference to) the button as usual, then, while handling the button click, create your spinner and set it as a subview of the button. It's probably also worth disabling the button to stop multiple clicks.
Something along the following lines should do the trick:
...
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(10, 10, 70, 40);
[button setTitle:#"Next" forState:UIControlStateNormal];
[button addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
...
- (void)click:(UIButton *)button {
[button setTitle:#"" forState:UIControlStateNormal];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner startAnimating];
spinner.frame = button.bounds;
[button addSubview:spinner];
button.enabled = NO;
// do your actual work...
}
I wrote a category that utilizes associated objects
UIButton+ActivityIndicator.h
// Created by reynaldo on 1/16/14.
#import <Foundation/Foundation.h>
#interface UIButton (ActivityIndicator)
- (void)startActivityIndicator;
- (void)stopActivityIndicator;
#end
UIButton+ActivityIndicator.m
// Created by reynaldo on 1/16/14.
#import <objc/runtime.h>
#import "UIButton+ActivityIndicator.h"
static char TITLE_KEY;
static char ACTIVITY_INDICATOR_KEY;
#implementation UIButton (ActivityIndicator)
- (void)startActivityIndicator {
objc_setAssociatedObject(self, &TITLE_KEY, self.currentTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self setTitle:#"" forState:UIControlStateNormal];
UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[self addSubview:activityIndicatorView];
activityIndicatorView.frame = CGRectMake(self.frame.size.width / 2, self.frame.size.height / 2. - 2, 7, 7);
[activityIndicatorView startAnimating];
objc_setAssociatedObject(self, &ACTIVITY_INDICATOR_KEY, activityIndicatorView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)stopActivityIndicator {
NSString *title = objc_getAssociatedObject(self, &TITLE_KEY);
UIActivityIndicatorView *activityIndicatorView = objc_getAssociatedObject(self, &ACTIVITY_INDICATOR_KEY);
if(activityIndicatorView) {
[activityIndicatorView removeFromSuperview];
}
if(title.length) {
[self setTitle:title forState:UIControlStateNormal];
}
}
#end

Help with iphone button pressed

I am trying to see which button was clicked on so I can preform the correct logic.
This is the code for the buttons:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(270, 423, 60, 60)];
[button addTarget:self action:#selector(buttonPressedAction:)
forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[[UIImage imageNamed:#"refreshicon.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0]
forState:UIControlStateNormal];
button.tag = 1;
UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 423, 60, 60)];
[button2 addTarget:self action:#selector(buttonPressedAction:)
forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[[UIImage imageNamed:#"login.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0]
forState:UIControlStateNormal];
button2.tag = 2;
[self.navigationController.view addSubview:button];
[self.navigationController.view addSubview:button2];
And this is how I call the buttonPressedAction:
- (void)buttonPressedAction:(id)sender
{
UIButton* button = (UIButton*)sender;
if(button.tag == 1)
{
NSLog(#"1");
}else
{
NSLog(#"2");
}
}
But when I use NSLog to see what the sender value is, it crashes.
Any advice for what's happening and how to correct it?
Now corrected :o) THANKS!
As other have pointed out, UIButton does not have a value property. I guess you are trying to detect which button was clicked. Here are two ways to do this:
Use the tag property one each button. I.e. button1.tag = 1, button2.tag = 2. You can then test which button was clicked with if(sender.tag == 1) etc. You could introduce constants for the numbers to make the code more readable.
If you keep a reference to the button, you can check if the reference is equal. Example: if(sender == self.button1)
Probably the best approach would be to give buttons that do different things different actions, but failing that, you could distinguish them by tag.
- (void)buttonPressedAction:(id)sender
{
UIButton* button = (UIButton*)sender;
// do something
}
If you were saving the pointers to the button objects you are creating, you could compare the pointers. Or you can just set the tag property for the button, and use that to switch behaviour.