How to set Uilabel text to nil +iphone - ios

I have dynamic UIButtons with subview is UIlabel.
My requirement is to display one label text in one button first time, after based on user selection(long press on the button) need to update the particular button subview label text and remove rest of the button subview label text.
I tried in this way
for (int i=0; i < [arr count]; i++)
{
UILabel *myLbl = [[UILabel alloc] initWithFrame:CGRectMake(30, 70, 60, 21)];
if (myissue.tag ==1) {
myLbl.text = #"Default";
}else {
myLbl.text = #"";
}
myLbl.backgroundColor = [UIColor clearColor];
myLbl.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
[myLbl setFont:[UIFont fontWithName:#"Helvetica" size:12]];
myLbl.textAlignment = NSTextAlignmentCenter;
myLbl.tag = i+1;
[myButton addSubview:defaultLbl];
[myLbl release];
}
And for retrieving the UILabel text
- (void)longPressTap:(UILongPressGestureRecognizer *)sender
{
if ([recognizer.view tag]) {
for (UIButton *btn in scrollView.subviews) {
UIButton *btnTag = (UIButton *)btn;
NSLog(#"--sv:%#", btn.subviews);
if (recognizer.view.tag == btnTag.tag){
[[btn.subviews objectAtIndex:3] text] ;
}else {
[[btn.subviews objectAtIndex:3] textAttributesForNil] ;
}
}
}
}
}
my problem is i was not able to selected button subview label text and removing rest of the button label text.
please help me.

You shouldnt need to add a label as a subview for a button, buttons already have their own text label that can be set using [button setTitle:(NSString *) forState:(UIControlState)]
and to remove the text just set seTitle:#""

Related

Custom View above a keyboard not working in ios9

Have added a custom view consisting of buttons on top of the keyboard. The buttons are being displayed correctly but on tapping on the buttons, the underlying keys of the keyboard are pressed instead of the button actions.
UIWindow* tempWindow = [UIApplication sharedApplication].windows.lastObject;
for (UIView *keyboard in [tempWindow subviews]) {
if ([[keyboard description] hasPrefix : #"<UIInputSetContainerView"]) {
for(int i = 0 ; i < [keyboard.subviews count] ; i++)
{
UIView* hostkeyboard = [keyboard.subviews objectAtIndex:i];
if([[hostkeyboard description] hasPrefix:#"<UIInputSetHost"] == YES){
[hostkeyboard addSubview:extraRow];
[hostkeyboard bringSubviewToFront:extraRow];
}
}
}
}
extraRow is the UIView consisting of buttons.
Is there anything missing ?
You could do just add a custom view to the keyboard as an inputAccessoryView. Then it just assign the button the correct target you want it to fire when clicked on
- (void)textFieldDidBeginEditing:(UITextField *)textField {
UIView * theView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
[theView setBackgroundColor: [UIColor greyColor]];
UITextField * txtTest = [[UITextField alloc] initWithFrame:CGRectMake(0, 5, theView.frame.size.width, 60)];
UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 65, 100, 30)];
[btn setTitle:#"Click my Button" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(alert:) forControlEvents:UIControlEventTouchUpInside];
// Just put this to see the items or customize the color
[txtTest setBackgroundColor:[UIColor whiteColor]];
[btn setBackgroundColor:[UIColor blueColor]];
// Need this to add it to the view
[theView addSubview:txtTest];
[theView addSubview:btn];
textField.inputAccessoryView = theView;
}
One thing you might want to consider is setting the extraRow's exclusiveTouch property to YES. As a disclaimer I haven't tried this example myself but I think the problem you are having is due to the view passing along the touch event.

How to change title color of a set of UIButtons created programmatically?

In my app I have created a few buttons programmatically using a for loop as shown below.It is for a HORIZONTAL TAB MENU
In the action,I have to highlight the selected button(and greyout the remaining button titles).How to do this?
It should look almost like the image below.
When a button is clicked,the clicked button title color should be
white and all other buttons should have a grey color.I know I can
access sender.titlecolor in the button action.But What about the other
buttons?
-(void)createButtons
{
float buttonMinX=10;
float buttonMinY=0;
scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _tabViewBackground.frame.size.width, _tabViewBackground.frame.size.height)];
ButtonIndex=0;
scrollView.showsHorizontalScrollIndicator = NO;
[_tabViewBackground addSubview:scrollView];
for (int i=0; i<_tabItemsListArray.count; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tintColor=[UIColor whiteColor];
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 1;
button.tag=i;
[button addTarget:self action:#selector(action:) forControlEvents:UIControlEventTouchUpInside];
UIFont *font1 = [UIFont fontWithName:#"HelveticaNeue-Thin" size:20.0f];
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSTextAlignmentCenter];
NSDictionary *dict1 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleNone),
NSFontAttributeName:font1,
NSParagraphStyleAttributeName:style};
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:[_tabItemsListArray objectAtIndex:i] attributes:dict1]];
[button setAttributedTitle:attString forState:UIControlStateNormal];
buttonWidth= [self getWidthOfRect:button.titleLabel];
button.frame = CGRectMake(buttonMinX,buttonMinY,buttonWidth,_tabViewBackground.frame.size.height);
buttonMinX+=buttonWidth+05;
sublayer = [[UIView alloc]init];
sublayer.backgroundColor = [UIColor greenColor];
sublayer.tag=kButtonSelectrorTag+i;
sublayer.frame = CGRectMake(button.frame.origin.x,button.frame.size.height-2, button.frame.size.width,2);
[scrollView addSubview:sublayer];
sublayer.hidden=YES;
if (ButtonIndex==i)
{
sublayer.hidden=NO;
}
button.backgroundColor=[UIColor clearColor];
[scrollView addSubview:button];
}
scrollView.backgroundColor = [UIColor blueColor];
scrollView.contentSize = CGSizeMake(buttonMinX+10,_tabViewBackground.frame.size.height);
}
-(CGFloat)getWidthOfRect:(UILabel*)titleLabel
{
CGFloat widthIs =[titleLabel.text boundingRectWithSize:titleLabel.frame.size options:NSStringDrawingUsesDeviceMetrics attributes:#{ NSFontAttributeName:titleLabel.font }context:nil].size.width;
widthIs = ceilf(widthIs);
// NSLog(#"the width of yourLabel is %f", widthIs);
return widthIs+30;
}
- (void)action:(UIButton*)sender
{
for (int i=0; i<_tabItemsListArray.count; i++)
{
UIView *tabSelector = (UIView *)[self.view viewWithTag:kButtonSelectrorTag+i];
[tabSelector setHidden:YES];
}
UIView *tabSelector = (UIView *)[self.view viewWithTag:kButtonSelectrorTag+sender.tag];
[tabSelector setHidden:NO];
}
I have a button selector below every button.I should show one buttonSelector at a time.It is working great using the code in the action:
I've notice that you are using setAttributedTitle:forState:. You can set attributes for title in the same way but for UIControlStateSelected also.
Then, if you set button.selected = YES; attributes from UIControlStateSelected will apply.
If you set button.selected = NO; attributes from UIControlStateNormal will apply.
EDIT:
You can create your buttons like this:
NSInteger numberOfButtons = 10;
NSMutableArray *menuButtonsMutableArray = [[NSMutableArray alloc] initWithCapacity:numberOfButtons];
for (int i = 0; i < numberOfButtons; i++) {
UIButton *button = [UIButton new];
//layout your button somehow
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(menuButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
[menuButtonsMutableArray addObject:button];
}
self.menuButtonsArray = [menuButtonsMutableArray copy];
Then in action method:
- (void)menuButtonDidTap:(UIButton *)sender {
for (UIButton *button in self.menuButtonsArray) {
button.selected = (button == sender);
}
}
#IBOutlet var AllButtons: [UIButton]!
for button in AllButtons {
if button.backgroundColor == UIColor.red {
button.backgroundColor = compare.backgroundColor
}
}
Drag and drop all your buttons in AllButtons, then use for loop to access all the buttons and do whatever you like to do.
This is a simple example, hope it helps.

How to ADD label inside infinite button?

This is my code:
-(void)scrollView
{
NSInteger buttonCount = 0;
NSInteger buttonSize = 0;
int divisible= 0;
buttonCount=[[arrFullSubCategory valueForKey:#"name"]count];
if(buttonCount==2)
{
divisible = 2;
buttonSize=self.view.frame.size.width/divisible;
}
else
{
divisible = 3;
buttonSize=self.view.frame.size.width/divisible;
}
[viewBtnScroll addSubview:self.scrollViewBtn];
for(int i=0;i<buttonCount;i++)
{
self.scrollViewBtn.scrollsToTop=YES;
self.scrollViewBtn.directionalLockEnabled=YES;
self.automaticallyAdjustsScrollViewInsets = NO;
UIButton *btn;
btn=[[UIButton alloc]initWithFrame:CGRectMake(buttonSize*i,0,buttonSize,self.scrollViewBtn.frame.size.height)];
[btn setTitle:[NSString stringWithFormat:#"%#",[[arrFullSubCategory objectAtIndex:i] valueForKey:#"name"]] forState:UIControlStateNormal];
btn.userInteractionEnabled=YES;
NSInteger tag=[[[arrFullSubCategory valueForKey:#"category"] objectAtIndex:i] integerValue];
[btn addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:tag];
highLight=[[UILabel alloc]initWithFrame:CGRectMake(buttonSize*i,10,btn.frame.size.width,20)];
highLight.backgroundColor=[UIColor greenColor];
highLight.hidden=YES;
[btn addSubview:highLight];
[self.scrollViewBtn addSubview:btn];
length = [[arrFullSubCategory valueForKey:#"name"] count];
}
self.scrollViewBtn.contentSize=CGSizeMake(buttonSize*buttonCount, self.scrollViewBtn.frame.size.height);
}
1.That button depend up on the coming json values.
2.That button size is calculated for the screen size.
3.i have created label as globally for some reason,and added that to subview of button ,initially it is hide ,when the button pressed that particular button label hidden=NO;
4.everything i have done perfectly,but my problem is How to give x.origin for the particular label?
5.From my code the label present only at end of the button not for all.
6.If i set x.origin as 0 then its present only at the initial button[first button].
7.That button present in scrollview .....
Simplest solution for this would be
create new UIView (lets name it MyView) of the size you want.
create UILabel of size you want and x and y with respect to MyView
and add it to MyView
Add MyView to your UIScrollView.
Then create a UIButton of the same dimensions as MyView and add it to you same UIScrollView
Important here is you add button to your UIScrollView and not MyView
and you are good to go .. hope this helps...
======= EDITS ======== Use the code as you need
float width = GridScrollView.frame.size.width;
int i,k=0;
for ( i= 0; i < imageArray.count; i+=4) {
for (int j =0; j<4; j++) {
if (i+j <nameArray.count) {
NSLog(#"i = %d j = %d k = %d",i,j,k);
UIActivityIndicatorView *spinner2 = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/4)];
[spinner2 startAnimating];
[GridScrollView addSubview:spinner2];
UIView *gridBox = [[UIView alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/4)];
// gridBox.backgroundColor=[UIColor whiteColor];
[GridScrollView addSubview:gridBox];
UIView *labelBack = [[UIView alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/16)];
labelBack.backgroundColor=[UIColor blackColor];
labelBack.alpha=0.5;
[GridScrollView addSubview:labelBack];
UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/16)];
nameLabel.text=nameArray[i+j];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.textColor=[UIColor whiteColor];
nameLabel.font=[UIFont fontWithName:#"Arial" size:12];
[GridScrollView addSubview:nameLabel];
UIButton *gridButton = [[UIButton alloc]initWithFrame:CGRectMake((width/4)*j ,(width/4)*k , width/4, width/4)];
[gridButton addTarget:self action:#selector(gridButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
gridButton.tag=i+j;
[GridScrollView addSubview:gridButton];
}
} k++;
}
[GridScrollView setContentSize:CGSizeMake(width, (width/4)*(i/4))];
[self.view addSubview:GridScrollView];

Switching UISwitch on/off by pressing on UILabel

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];
}

removeObjectFromSuperView not working with if statement

I have a button that when pressed is supposed to hide the status bar and place text in its spot. Then, when the button is pressed the label is supposed o be removed from the view and the status bar will re-appear. The first part works -- the status bar is hidden and the label is placed on the view, the problem is when I press the button a second time (to remove the text and put back the status bar). The status bar re-appears but the label is not being removed from the view. To achieve this I am using an if statement. I am also using removeObjectFromSuperView which is the thing that is not working.
Here is the code:
- (IBAction)buttonPressed:(id)sender {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 21)];
label.text = #"This is a test";
[label setFont:[UIFont systemFontOfSize:13]];
label.textAlignment = NSTextAlignmentCenter;
if (hidden == NO) {
[UIApplication sharedApplication].statusBarHidden = YES;
[self.view addSubview:label];
hidden = YES;
}else if (hidden == YES) {
[UIApplication sharedApplication].statusBarHidden = NO;
[label removeFromSuperview];
hidden = NO;
}
}
Thanks
Edit: Here is what the problem looks like:
You need to track your label outside of the buttonPressed: method. Right now you are creating a new label every time the button is pressed then removing that same label.
So for example:
#interface MyViewController () {
UILabel *label;
}
- (IBAction)buttonPressed:(id)sender {
if (hidden == NO) {
[UIApplication sharedApplication].statusBarHidden = YES;
label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 21)];
label.text = #"This is a test";
[label setFont:[UIFont systemFontOfSize:13]];
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
hidden = YES;
} else if (hidden == YES) {
[UIApplication sharedApplication].statusBarHidden = NO;
[label removeFromSuperview];
label = nil;
hidden = NO;
}
}
You can also set label = nil; once you remove it from the super view.

Resources