UIButton's titleLabel.text is not displayed on Cocoa Touch - objective-c

After I create a new UIButton at runtime, and set its titleLabel's text, the button's text is still not displayed.
What am I doing wrong?
-(IBAction) cloneMe: (id) sender{
if (!currentY) {
currentY = [sender frame].origin.y;
}
UIButton *clone = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect cloneFrame = [sender frame];
cloneFrame.origin.y += currentY + cloneFrame.size.height + 30;
clone.frame = cloneFrame;
[clone titleLabel].text = #"I'm a clone";
[[sender superview] addSubview:clone];
currentY = cloneFrame.origin.y + cloneFrame.size.height;
}

You need:
[clone setTitle:#"I'm a clone" forState:UIControlStateNormal];
Check out the UIControl API docs for other valid values for the forState: argument.

Use setTitle:forState: to set the title of a button.

Related

Highlighting the button with sender tag

I have 7 buttons on my storyboard, I have associated a tag number to each of the button. And all the buttons are hooked up to a single IBAction.
In my action method I have a switch statement like switch ([sender tag])
which run the appropriate action according to the tag. This is all working.
But I want to add a functionality where selected button is highlight and rest of them in normal state.
You can create property with tags:
#property (nonatomic, strong) NSArray *tags;
Somewhere (for example, in viewDidLoad) initialize it with values used in storyboard:
tags = #[#1, #2, #3, #4, #5]
And select buttons using this tags
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i = 0; i < tags.count; i++) {
UIButton *button = [self.view viewWithTag:tags[i]];
button.selected = (button.tag == sender.tag);
}
}
Or you can create IBOutlets for every 7 buttons and create array for it.
array = #[outlet1, ..., outlet7]
And select buttons using outlets
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i = 0; i < array.count; i++) {
UIButton *button = array[i];
button.selected = (button.tag == sender.tag);
}
}
Hope this can give you some idea:
- (void)setupButtons {
for (int i = 0; i < 7; i++) {
CGFloat width = self.view.frame.size.width / 7;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 100, width, 30)];
[self.view addSubview:button];
button.tag = 1000 + i;
[button setTitle:[NSString stringWithFormat:#"%d", i] forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
if (i == 0) {
// default first button selected
button.selected = YES;
}
}
}
- (void)buttonClicked:(UIButton *)sender {
for (int i = 0; i < 7; i++) {
UIButton *button = [self.view viewWithTag:(1000+i)];
button.selected = (button.tag == sender.tag);
}
}

How do I change a button's color when pressed and reset to original color when a different button are pressed?

I have created buttons dynamically based on array count ,if i pressed it will move to next page .i want to change the background color of the button if it is pressed .i pressed 1st button its background color should changed ,and den if i pressed anyother buttons the first pressed button should get into default color of the button , and the new pressed button's background color should changed ,
please help me to do this ,On button clicked method i have tried like this ,
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
selected = YES;
if (selected) {
[btn setBackgroundColor:[UIColor redColor]];
}
}
and this my button creation code ,
int buttonheight = 30;
int horizontalPadding = 20;
int verticalPadding = 20;
int totalwidth = self.view.frame.size.width;
int x = 10;
int y = 150;
for (int i=0; i<array.count; i++)
{
NSString* titre = [array objectAtIndex:i];
CGSize contstrainedSize = CGSizeMake(200, 40);//The maximum width and height
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:20.0], NSFontAttributeName,
nil];
CGRect frame = [titre boundingRectWithSize:contstrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil];
int xpos = x + CGRectGetWidth(frame);
if (xpos > totalwidth) {
y =y +buttonheight+ verticalPadding;
x = 10;
}
UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.word = word;
NSLog(#"%#", NSStringFromCGRect(frame));
word = [UIButton buttonWithType:UIButtonTypeRoundedRect];
word.frame = CGRectMake(x, y, CGRectGetWidth(frame)+5, CGRectGetHeight(frame));
[word setTitle:titre forState:UIControlStateNormal];
[word setTitle:titre forState:UIControlStateSelected];
word.backgroundColor = [UIColor colorWithRed:30.0/255.0 green:134.0/255.0 blue:255.0/255.0 alpha:1.0];
[word setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[word setTag:i];
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)allBtnSharedTappedevent:(id)sender {
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
//loop through all your buttons
for(UIView *view in [self.view subviews]){
if([view isKindOfClass:[UIButton class]]){
if(view != btn){
UIButton* btn1 = (UIButton*) view;
[btn1 setBackgroundColor:[UIColor grayColor]];
}
}
}
}
Keep the buttons in an array.
#property (nonatomic, copy, readonly) NSArray<UIButton *> *buttons;
Then in your method that handles the tap, do something like this.
- (IBAction)buttonTapped:(UIButton *)sender {
// Loop through all buttons, clearing the background color
for (UIButton *button in self.buttons) {
button.backgroundColor = [UIColor clearColor];
}
// Set the background color for the selected button
sender.backgroundColor = [UIColor redColor];
}
You should avoid using the tag property of UIView, it will just cause you headaches down the road.
give your button tag number like 1,2,3,4 ... etc
then
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
loop through all your buttons
for(int i = 1;i <= total numbers of button; i++){
if(btn.tag != i){
UIButton* btn1 = [myView viewWithTag:i];
[btn1 setBackgroundColor:[UIColor graycolor]];
}
}
}

Recognize a UIButton Tap inside a UIScrollView

I have a UIScrollView into which I add UIImageViews dynamically.
On the storyboard
After running the program
The code for adding an image is on my custom class. The class isn't assigned to any view:
- (id)initWithModel:(UIScrollView *)scroller page:(NSInteger)page image:(UIImage*)image{
self = [super init];
if (self) {
_scrollView = scroller;
_imageScrollIndex = page;
_image = image;
_frame = _scrollView.bounds;
_frame.origin.x = _frame.size.width * _imageScrollIndex;
_frame.origin.y = 0.0f;
_frame = CGRectInset(_frame, 10.0f, 0.0f);
_imageView = [[UIImageView alloc] initWithImage:_image];
_imageView.contentMode = UIViewContentModeScaleAspectFit;
_imageView.frame = _frame;
//adding delete image button
CGRect frame = _imageView.frame;
frame.origin.x = frame.size.width/2;
frame.origin.y = -frame.size.height/2+45;
//_imageView.userInteractionEnabled = YES;
UIButton *deleteImgButton = [[UIButton alloc] initWithFrame:frame];
deleteImgButton.userInteractionEnabled = YES;
[deleteImgButton addTarget:self action:#selector(clickedDeleteButton:)forControlEvents:UIControlEventTouchUpInside];
[deleteImgButton setImage:[UIImage imageNamed:#"close.png"] forState:UIControlStateNormal];
[_imageView addSubview:deleteImgButton];
////
[_scrollView addSubview:_imageView];
}
return self;
}
- (void)clickedDeleteButton:(UIButton*)button
{
printf("hi:\n");
}
I want to be:
Be able to recognize scroll event (Thus I think I need to keep the userinteractionenabled YES for the scrollView
Be able to recognize a tap on the delete button of the image
Any ideas how?
_scrl_ipad.contentSize = CGSizeMake(768,273 * temp);
_scrl_ipad.showsVerticalScrollIndicator=NO;
UIButton *btn_scrl=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_scrl setFrame:CGRectMake(0,0, 328, 243)];
btn_scrl.tag=i-1;
[btn_scrl addTarget:self action:#selector(btn_scrl_tag:) forControlEvents:UIControlEventTouchUpInside];
[_scrl_ipad addSubview:btn_scrl];
-(IBAction)btn_scrl_tag:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(#"%d",btn.tag);
}

Add texfield in runtime in IOS

I want to make an "add" button to add as many textfields as i want in my scroll view.
I did this already
UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
[self.scrollView addSubview:text];
But is not working.
Thanks!
If this is your complete button code:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
// add this
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
// continue
[self.mainScroll addSubview:button];
Then add this somewhere:
- (void) buttonPressed:(UIButton *)button {
UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
text.backgroundColor = [UIColor greenColor]; // just to make sure it's showing up.
[self.scrollView addSubview:text];
}
First create common function like this,
-(void)setTextfieldStyle:(UITextField *)pTmpTextField
{
pTmpTextField.borderStyle = UITextBorderStyleRoundedRect;
pTmpTextField.font = [UIFont systemFontOfSize:15];
pTmpTextField.placeholder = #"First Name";
pTmpTextField.autocorrectionType = UITextAutocorrectionTypeNo;
pTmpTextField.keyboardType = UIKeyboardTypeDefault;
pTmpTextField.returnKeyType = UIReturnKeyDone;
pTmpTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
pTmpTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
pTmpTextField.delegate = self;
}
and use this for creating UITextFiled,
int y = 0;
for(int i=0;i < 5;i++)
{
UITextField *txtTemp=[[UITextField alloc]initWithFrame:CGRectMake(0, y, 300, 31)];
txtTemp.tag = i;
[self setTextfieldStyle:txtTemp];
[self.view addSubview:txtTemp];
[txtTemp release];
y+=36;
}
This is UITextField's delegate method,
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"%#",textField.text);
}
Hope this works for you as this works for me. only keep this in mind that add the text fields to your scroll view.
In the example am adding them to my view!

Scroll to center of UIScrollview clicked UIButton added programmatically EDITED

I have a scrollview of scrollview of UIbuttons build like this:
-(void) loadCompeticionSlide{
float x=0;
for (int i = 0; i < [categoriasArray count]; i++) {
NSDictionary *categoria = [categoriasArray objectAtIndex:i];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString *titleString = [categoria valueForKey:#"competicion"]; // get button title
btn.titleLabel.font = [UIFont boldSystemFontOfSize:11.0];
CGSize fontSize = [titleString sizeWithFont:[UIFont systemFontOfSize:11.0]];
CGRect currentFrame = btn.frame;
CGRect buttonFrame = CGRectMake(x, currentFrame.origin.y, fontSize.width + 22.0, fontSize.height + 12.0);
[btn setFrame:buttonFrame];
x = x + fontSize.width + 35.0;
[btn setTitle:titleString forState: UIControlStateNormal];
int idc = [[categoria valueForKey:#"idc"]intValue];
[btn addTarget:self action:#selector(cambiarCompeticion:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:idc];
[self.competicionSlide addSubview:btn];
}
//[competicionSlide setBackgroundColor:[UIColor whiteColor]];
competicionSlide.contentSize = CGSizeMake(350,35);
competicionSlide.layer.cornerRadius = 11;
competicionSlide.layer.masksToBounds = YES;
}
Then, in the added selector cambiarCompeticion:, I got the button clicked, here I need to use scrollRectToVisible: to get the clicked UIButton scrolled to the center of the UIScrollview that contains it, but I don't know how to do it.
This is the selector method triggered by button selection where I understand scrollRectToVisible: has to be called:
-(void)cambiarCompeticion:(UIButton*)boton{
int idCompeticion;
idCompeticion = boton.tag;
switch (idCompeticion) {
case 1:
[self tablaLigaRegular];
break;
case 5:
[self tablaCoparey];
break;
case 10:
[self tablaPlayOff];
break;
}
}
here are the details in images, in first image blue arrow indicates previous state of the partial hidden left button and the move to do to the middle of scroll view once it is clicked:
many thanks
Your boton parameter (from the cambiarCompeticion: selector) has everything you need. Just call like this (assuming that "competicionSlide" is an UIScrollView) :
[self.competicionSlide scrollRectToVisible:boton.frame];
Good luck !