Accessing UILabel created on run time - ios

I have created UILabel (lblCount) and UIButton (btnAdd) on a UIButton (Add Item Button)'s action method. The new UILabel and UIButton is added to scrollview. The UILabel (lblCount) shows count of UIButton (btnAdd) tapped. Here, addBtnClickCount is an integer which counts the number of click.
UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake( 50, 100*addBtnClickCount, 25, 25)];
lblCount.text = [NSString stringWithFormat:#"%d",count];
lblCount.tag = addBtnClickCount;
lblCount.textColor = [UIColor whiteColor];
lblCount.textAlignment = NSTextAlignmentCenter;
[self.scrollView addSubview:lblCount];
addBtnClickCount = addBtnClickCount+1;
There will be multiple label (lblCount) and button (btnAdd) when user taps Add Item Button. I want to access particular label for particular add button and display the count.

You have already set tag on your label. Create a mutable array labelArray and add label to it. To access the particular label do following code on add button's action.
-(void)addItem:(UIButton*)button{
UILabel* lblShowCount = [_labelArray objectAtIndex:[button tag]];
lblShowCount.text = [NSString stringWithFormat:#"%d", [lblShowCount.text integerValue]+1];
}

Here i understand that #Hem Poudyal, know's that with help of viewWithTag.he will get output. but don't know how to achieved that. so i am describing over here.
Step 1: Here i am adding UILabel and UIButton to self.view instead of UIScrollView. i hope you can convert it as UIScrollView. here i applied some relation between UILabel tag and UIButton tag. that you can see in below code.
for (int i=0; i<10; i++) {
UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake( 50, (i*50)+((i+1)*5), 100, 50)];
lblCount.text = [NSString stringWithFormat:#"%d",0];
lblCount.tag = [[NSString stringWithFormat:#"%d%d",i,i] integerValue];
lblCount.backgroundColor = [UIColor yellowColor];
lblCount.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:lblCount];
UIButton* btnTemp = [UIButton buttonWithType:UIButtonTypeCustom];
btnTemp.tag = i;
btnTemp.backgroundColor = [UIColor redColor];
[btnTemp addTarget:self action:#selector(btnTempClick:) forControlEvents:UIControlEventTouchUpInside];
btnTemp.frame = CGRectMake( 150, (i*50)+((i+1)*5), 100, 50);
[btnTemp setTitle:[NSString stringWithFormat:#"Button : %d",i] forState:UIControlStateNormal];
[self.view addSubview:btnTemp];
}
Step 2: In UIButton selector method, Do the following things.
-(IBAction)btnTempClick:(id)sender{
UIButton* btnInner = sender;
NSInteger lblTagbaseOnButtonTag = [[NSString stringWithFormat:#"%ld%ld",btnInner.tag,btnInner.tag] integerValue];
UILabel* lblReceived = (UILabel*)[self.view viewWithTag:lblTagbaseOnButtonTag];
lblReceived.text = [NSString stringWithFormat:#"%ld",[lblReceived.text integerValue]+1];
}
And Output is :

You should have an array that you add the labels and buttons too (this could be one array containing a dictionary or custom class or multiple arrays). Now, when a button is tapped you can find where it is in the array and get the corresponding label to update.
The cheat way is to set the tag of the buttons and labels so you can find one from the other using viewWithTag:.

You need to set unique tag value while creating the labels and buttons and by using viewWithTag: you can access the respective ui container.

Related

objective c How to access and change dynamically created button background color in a uiscrollview

As you can see in the screenshot I have created multiple buttons dynamically in a UI scroll view. Every button actually holds a date action upon which specific events to that date loads into table. UI Scroll view is global element in the code which can be accessed by any method in the controller.
What I wanted now is access a button (when someone chooses a date to see events on that date) in that scrollview and change its background color. For your convenience I have added the whole code for date and scrollview. Please also note that data are loading from remote server.
Link to the screenshot is as follows
Please forgive me if you see anything wrong in typing. This is my first question in stack.
luckyDateScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(22, 2, lucky_screen_width-45, 23)];
luckyDateScrollView.showsHorizontalScrollIndicator = NO;
CGFloat paperWidth = 50;
int numberOfPapers = [dateRanges count];
for (int i=0; i<[dateRanges count]; i++) {
//NSLog(#"%d: %#", i, dateRange[i]);
//php like exploding with separator |
NSArray *dateString = [dateRanges[i] componentsSeparatedByString:#"|"];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake( 5+ (paperWidth+4) * i , 0, paperWidth, luckyDateScrollView.bounds.size.height)];
btn.titleLabel.font = [UIFont fontWithName:#"Arial" size:11.0f];
[btn setTitle: [NSString stringWithFormat:#"%#",dateString[0]] forState:UIControlStateNormal];
//dateResendButton
[btn setTag:i];
[btn addTarget:self
action:#selector(byDateFilterButton:)
forControlEvents:UIControlEventTouchUpInside];
if([today isEqualToString:dateString[1]]){
[GlobalMethods makeRoundedView:btn WithColorString:#"#ffffff" BGColorString:#"#004D00"];
}else{
[GlobalMethods makeRoundedView:btn WithColorString:#"#ffffff" BGColorString:GlobalVariables.initGV.BlackColor];
}
//[GlobalMethods makeRoundedView:btn WithColorString:#"#ffffff" BGColorString:#"#FF0000"];
[luckyDateScrollView addSubview:btn];
}
contentSize = CGSizeMake( 10 + (paperWidth+4) * numberOfPapers, luckyDateScrollView.bounds.size.height);
luckyDateScrollView.contentSize = contentSize;
// [GlobalMethods makeRoundedView:aScrollView WithColorString:#"#ffffff" BGColorString:GlobalVariables.initGV.BlackColor];
[dateUIView addSubview:luckyDateScrollView];
luckyDateBtnLeftScroll = [[UIButton alloc] initWithFrame:CGRectMake(5, 2, 20, 23)];
[luckyDateBtnLeftScroll setBackgroundImage:[UIImage imageNamed:#"arrow_g_icon_left"] forState:UIControlStateNormal];
[luckyDateBtnLeftScroll addTarget:self action:#selector(dateSetScrollToLeft:) forControlEvents:UIControlEventTouchUpInside];
[dateUIView addSubview:luckyDateBtnLeftScroll];
luckyDateBtnRightScroll = [[UIButton alloc] initWithFrame:CGRectMake(lucky_screen_width-25, 2, 20, 23)];
[luckyDateBtnRightScroll setBackgroundImage:[UIImage imageNamed:#"arrow_g_icon"] forState:UIControlStateNormal];
[luckyDateBtnRightScroll addTarget:self action:#selector(dateSetScrollToRight:) forControlEvents:UIControlEventTouchUpInside];
[dateUIView addSubview:luckyDateBtnRightScroll];
//ViewCollapse.backgroundColor = [UIColor colorWithCGColor: #"#FFD80D"];
If I understand your question correctly you can simply change the background of your button in the byDateFilterButton: method. It should have a sender parameter which would be the button in question.
If you also need to change the background of the other buttons back to normal, you need to keep a reference to them, probably in an array (or dictionary - if you have many buttons and need fast access).
I modified byDateFilterButton method in a following way. Thanks to this SO post Access all buttons in uiscollview
for (id obj in luckyDateScrollView.subviews) {
NSString *classStr = NSStringFromClass([obj class]);
if ([classStr isEqualToString:#"UIButton"]) {
UIButton *button = (UIButton*)obj; //NSLog(#"buttonn tag %ld",(long)button.tag);
if(sender.tag == button.tag){ // currently selected button
[GlobalMethods makeRoundedView:button WithColorString:#"#ffffff" BGColorString:#"#555454"];
}
else{ // the rest of buttons
[GlobalMethods makeRoundedView:button WithColorString:#"#ffffff" BGColorString:GlobalVariables.initGV.BlackColor];
}
}
}

Add Multiple UIButton to a ScrollView

Hej guys, i'm trying to add multiple buttons in a scrollview dynamically
so far, I have this code
for (int i = 0; i < numberOfButtonInMenu; i++)
{
UIButton *aButton = [UIButton new];
UILabel *tButton = [UILabel new];
UILabel *sButton = [UILabel new];
UIImageView *iButton = [UIImageView new];
tButton = title;
sButton = subtitle;
iButton = image;
tButton.hidden = NO;
sButton.hidden = NO;
iButton.hidden = NO;
[tButton setText:Titles[i]];
[sButton setText:Subtitles[i]];
[tButton sizeToFit];
[sButton sizeToFit];
iButton.image = [UIImage imageNamed:Images[i]];
aButton.frame = CGRectMake(xCoord, yCoord, screenWidth, buttonHeight);
[aButton addTarget:self action:#selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[aButton addSubview:tButton];
[aButton addSubview:sButton];
[aButton addSubview:iButton];
[multiMenuScroll addSubview:aButton];
yCoord += buttonHeight + buffer;
}
}
I set all my design before this for.
When I display my multiMenuScrollView, I end up with only the last button displayed.
(so for numberOfButtonInMenu = 3; I'll have only the third button display)
it look like this : http://i.stack.imgur.com/5UU6S.jpg
Between the "Explore" and the "Around You" there's two others Button, but with nothing in it, it's kinda weird.
Do you guys have any ideas of what I'm doing wrong ?
because you add again tButton sButton iButton in aButton1 to aButton3. show there're will show only in last view (aButton3). If want to add tButton sButton iButton to each button like your code, you need init new tButton sButton iButton in each for loop.
Wrong code:
tButton = title;
sButton = subtitle;
iButton = image;
it must be somethings like:
UILabel *tButton = [[UILabel alloc] initWithFrame:...];
UILabel *sButton = [[UILabel alloc] initWithFrame:...];
UIImageView *iButton = [[UIImageView alloc] initWithFrame:...];
No wonder...
You are not setting the frame correctly. In the for loop, each time you are creating a new button UIButton *aButton = [UIButton new]; and adding subview to multiMenuScroll. All of them getting added but at the same place. So, in the end only 3rd button shows up.
You would need to set the frame of your buttons correctly.
UIButton *aButton = [[UIButton alloc] initWithFrame:<Set_Your_Frame>]; // Change X or Y value as per for loop iteration.
As a side note, you are naming your labels as button suffix like tButton, sButton. Nothing wrong in it programmatically but they confuse!
vwScroll = name of scroll view
tagsArray = Array of NSStrings. These strings will be the text of labels which will add to scroll view in horizontal manner
-(void)setScrollViewWithArray:(NSArray *)tagsArray{
CGFloat xAxis = 0.0f;
CGFloat gapBwLabels = 10.0f;
[vwScroll.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
for (int i = 0; i<tagsArray.count; i++) {
NSString *tagName = [tagsArray objectAtIndex:i];
CGSize sizeOfTagString = [self getSizeOfText:tagName];
CGFloat width = sizeOfTagString.width+gapBwLabels;
CGRect tagLabelframe = CGRectMake(xAxis, 2, width, 30);
UILabel *lblTag = [[UILabel alloc]initWithFrame:tagLabelframe];
[self setLabel:lblTag withBackgroundColor:[UIColor whiteColor]];
[lblTag setText:tagName];
[vwScroll addSubview:lblTag];
xAxis = xAxis + width + gapBwLabels;
}
[vwScroll setContentSize:CGSizeMake(xAxis, vwScroll.frame.size.height)];
}

UIStepper valueChanged.

I'm making an iphone app and I have met a problem..
I'm making sub views which contains labels and a UIStepper..
They are made by a for loop like so:
//subView to contain one ticket
UIView *ticketTypeView = [[UIView alloc]initWithFrame:CGRectMake(10, y, 1000, 60)];
if(ticketCount%2){
ticketTypeView.backgroundColor = [UIColor lightGrayColor];
}
[self.view addSubview:ticketTypeView];
//label for ticket type name
UILabel *ticketType = [[UILabel alloc]initWithFrame:CGRectMake(10, 3, 500, 50)];
[ticketType setText:string];
[ticketType setFont:[UIFont fontWithName:#"Helvetica neue" size:20.0]];
[ticketTypeView addSubview:ticketType];
//UIStepper for ticket amount
UIStepper *stepper = [[UIStepper alloc]initWithFrame:CGRectMake(500, 16, 0, 0)];
stepper.transform = CGAffineTransformMakeScale(1.2, 1.2);
[ticketTypeView addSubview:stepper];
//label for price pr. ticket
UILabel *pricePrTicket = [[UILabel alloc]initWithFrame:CGRectMake(620, 5, 100, 50)];
[pricePrTicket setText:#"1000.00 Kr."];
[ticketTypeView addSubview:pricePrTicket];
//totalPrice label
UILabel *totalTypePrice = [[UILabel alloc]initWithFrame:CGRectMake(900, 5, 100, 50)];
[totalTypePrice setText:#"0.00 Kr."];
[ticketTypeView addSubview:totalTypePrice];
Now.. How do I add a IBAction valueChanged for my UIStepper? the stepper is supposed to take the count, multiply it by the pricePrTicket and display it in the totalPrice label..
Any help or hint will be much appreciated :)
You'll need to assign unique tag to all your subviews of ticketTypeView (each should be unique) then follow #thedjnivek answer. When you get call - (void) stepperChanged:(UIStepper*)theStepper method, get totalPrice label object like this,
UILabel *ticketprice = (UILabel *)[theStepper.superview viewWithTag:kTagPriceTicket];
check if label object is not nil,
if(ticketprice) {
ticketprice.text = theStepper.value * pricePrTicket;
}
In your for loop where you're creating ticketTypeView and other labels.
Your label tag should be unique for labels and the same for individual ticketTypeView views.
Create tags like this (you can give any integer for tags),
#define kTagTicketType 110
#define kTagPriceTicket 111
#define kTagTotalTypePrice 112
...
...
...
[ticketType setTag:kTagTicketType]; //NOTE this
[pricePrTicket setTag:kTagPriceTicket]; //NOTE this
[totalTypePrice setTag:kTagTotalTypePrice]; //NOTE this
Write above lines before adding each of the label.
You have to set the target with addTarget:action: like this :
[stepper addTarget:self action:#selector(stepperChanged:) forControlEvents:UIControlEventValueChanged];
- (void) stepperChanged:(UIStepper*)theStepper{
//This method would be called on UIControlEventsValueChanged
}
I hope that can help you ;)

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

Tableview with custom UIView , adding labels overlaps

I am trying to implement ibooks bookshelf like functionality and I use GSBookShelf which is pretty simple and straight forward, it adds button as cells and it works great.
I want to add some labels to each button, I succeed but once in a while lets say 2 out of 5 times labels overlaps from previous buttons label.
normally like this
Sometime this happens:
Code:
- (UIView *)bookShelfView:(GSBookShelfView *)bookShelfView bookViewAtIndex:(NSInteger)index {
NSDictionary *currentArticle = [_bookArray objectAtIndex:index];
static NSString *identifier = #"bookView";
MyBookView *bookView = (MyBookView *)[bookShelfView dequeueReuseableBookViewWithIdentifier:identifier];
if (bookView == nil) {
bookView = [[MyBookView alloc] initWithFrame:CGRectZero];
bookView.reuseIdentifier = identifier;
[bookView addTarget:self action:#selector(bookViewClicked:) forControlEvents:UIControlEventTouchUpInside];
}
[bookView setIndex:index];
[bookView setSelected:[(NSNumber *)[_bookStatus objectAtIndex:index] intValue]];
//[bookView setFileName:[currentArticle objectForKey:#"name"] ];
//[bookView setFileName:[currentArticle objectForKey:#"name"] :index];
UIImage *image = nil;
image = [self returnCellImagefor:[currentArticle objectForKey:#"imagename"]];
[bookView setBackgroundImage:image forState:UIControlStateNormal];
UILabel *_fileLabel=nil;
_fileLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 180, 200, 46)];
_fileLabel.text=[currentArticle objectForKey:#"name"];
_fileLabel.textColor=[UIColor whiteColor];
_fileLabel.backgroundColor=[UIColor clearColor];
_fileLabel.font = [UIFont fontWithName:#"Gill Sans" size:16];
//_fileLabel.textAlignment=UITextAlignmentCenter;
_fileLabel.textAlignment = NSTextAlignmentCenter;
_fileLabel.numberOfLines=0;
_fileLabel.lineBreakMode = UILineBreakModeWordWrap;
[_fileLabel sizeToFit];
[bookView addSubview:_fileLabel];
return bookView;
}
Images are good they never overlap but label does it sometimes.
Any idea why this is happening?
Where did you put bookShelfView function at? Show your TableView code. I bet the problem you have is that when you scroll down in table bookShelfView is being called again. Your label is being created twice for two different values.
That's the only way you see that overlap happening, this is being initiated over and over again
_fileLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 180, 200, 46)];
I would check your TableView Code. I had asked a similar question before. (not exact). Check it out UITableView and UILabel repeating

Resources