Can't hide created UIButton - iphone

I have three UIButtons which display in a random order using:
NSMutableArray *indexArray = [NSMutableArray arrayWithObjects:
[NSValue valueWithCGRect:CGRectMake(20, 187, 280, 44)],
[NSValue valueWithCGRect:CGRectMake(20, 258, 280, 44)],
[NSValue valueWithCGRect:CGRectMake(20, 330, 280, 44)], nil];
//Randomize the array
NSUInteger count = [indexArray count];
for (NSUInteger i = 0; i < count; ++i) {
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[indexArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
//Assign the frames
button1.frame = [((NSValue *)[indexArray objectAtIndex:0]) CGRectValue];
button2.frame = [((NSValue *)[indexArray objectAtIndex:1]) CGRectValue];
button3.frame = [((NSValue *)[indexArray objectAtIndex:2]) CGRectValue];
For some reason I an unable to hide these buttons after they display a number of items. I have tried for example
button1.hidden = YES; and also
[self.button1.hidden = YES];
Any ideas? Any help would be most appreciated.
Jamie

Pass tag to Buttons and use below code
for (UIButton *btn in [self.view subviews])
{
if (btn.tag==1)
{
[btn removeFromSuperview];
}
}
and your problem will be resolved and revert me..

These buttons are IBOUTLET?
You can think of another way to hide
like, '[UIView viewWithTag:(NSInteger)]
sample code is here
UIButton *tmpBtn = (UIButton *)[self.view viewWithTag:1]; // tag is your choice
tmpBtn.hidden = YES

To do this I use this:
if ([questions count]== 11)
{ button1.hidden = YES; button2.hidden = YES; button3.hidden = YES }
I would suggest you check two things:
that you effectively take the branch;
that your button* variables are not nil.
e.g.:
if ([questions count]== 11)
{
NSLog(#"Enter branch with %x, %x, %x", button1, button2, button3);
button1.hidden = YES; button2.hidden = YES; button3.hidden = YES;
}
(ignore the warning that you will get on NSLog).

Related

Identifying an UIImageView without tag

I have some generic generated ImageViews in a scrollView each of these images have 2 gestureRecognizer for single/double tapping on the ImageView. Now my problem is how to identify whether the ImageView was tapped for first or second time. In some scenarios it's easy to use the tag of an ImageView, but I have two different gestureRecognizer on each ImageView and every gestureRecognizer uses a different identification method based on the tag number, to identify the image.
Here I generate the ImageViews dynamically:
-(void) initLevels{
_level = [Level alloc];
_unit = [Unit alloc];
self->_units = [[NSMutableArray alloc] init];
_keys = [[NSMutableArray alloc] init]
;
int x = 0;
int y = 0;
int i = 0;
for (NSObject *object in self->_levels) {
if ([object isKindOfClass:_level.class] && i != 0) {
x = x + MARGIN_RIGHT + OBJECT_WIDTH;
y = 0;
}
else if ([object isKindOfClass:_unit.class]){
_unit = (Unit *) object;
[self->_units addObject:_unit.description];
UIImageView *imageView = [[UIImageView alloc] initWithImage:self.box];
[imageView setFrame:CGRectMake(x, y, OBJECT_WIDTH, BOX_HEIGHT)];
imageView.highlighted = TRUE;
imageView.tag = i; //when this is not outlined the gestureRecognizer for singleTapping works but on the other hand the double tap gestureRecognizer just works for the first object, because its' tag is set on 0.
UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(unitDoubleTapped:)];
doubleTapGesture.numberOfTapsRequired = 2;
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:doubleTapGesture];
UITapGestureRecognizer *singleTapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(unitSingleTapped:)];
singleTapGesture.numberOfTapsRequired = 1;
//telling the singleTapGesture to fail the doubleTapGesture, so both doesn't fire at the same time
[singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
[imageView addGestureRecognizer:singleTapGesture];
UILabel *labelHeadline = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 220, 20)];
[labelHeadline setFont:[UIFont boldSystemFontOfSize:12]];
labelHeadline.textAlignment = NSTextAlignmentCenter;
[labelHeadline setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
labelHeadline.text = _unit.headline;
labelHeadline.numberOfLines = 0;
[labelHeadline sizeToFit];
UILabel *labelPrice = [LabelUtils deepLabelCopy:labelHeadline withText:[NSString stringWithFormat:#"Price: %#",_unit.price] withFrame:NO];
[labelPrice setTextAlignment:NSTextAlignmentLeft];
[labelPrice setFrame:CGRectMake(labelHeadline.frame.origin.x, labelHeadline.frame.origin.y + labelHeadline.frame.size.height + 2, 220, 20)];
UILabel *labelCRM = [LabelUtils deepLabelCopy:labelHeadline withText:[NSString stringWithFormat:#"CRM: %#", _unit.crm] withFrame:NO];
[labelCRM setTextAlignment:NSTextAlignmentLeft];
[labelCRM setFrame:CGRectMake(labelPrice.frame.origin.x, labelPrice.frame.origin.y + labelPrice.frame.size.height + 2, 220, 20)];
UITextView *textView= [[UITextView alloc] initWithFrame:CGRectMake(0,0, OBJECT_WIDTH, OBJECT_HEIGHT)];
[textView addSubview:labelHeadline];
[textView addSubview:labelPrice];
[textView addSubview:labelCRM];
[textView setUserInteractionEnabled:NO];
[textView setEditable:NO];
textView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0];
textView.textAlignment = NSTextAlignmentLeft;
[imageView addSubview:textView];
[_scrollView addSubview:imageView];
y = y + MARGIN_BOTTOM + BOX_HEIGHT;
}
[self->_keys addObject:[NSNumber numberWithInt:i]];
i++;
}//remove the last keys which are to much in the _keys array
while ([self->_keys count] > ([self->_units count])) {
[_keys removeLastObject];
i--;
}
self.contents = [NSDictionary dictionaryWithObjects:self->_units forKeys:_keys];
}
Here is the code for the two gesture Recognizer
-(void)unitDoubleTapped:(UIGestureRecognizer *)gestureRecognizer{
self->_unitViewForDoubleTapIdentification = (UIImageView *)gestureRecognizer.view;
switch (self->_unitViewForDoubleTapIdentification.tag) {
case 0:
[_unitViewForDoubleTapIdentification setHighlightedImage:self.transparentBox];
self->_unitViewForDoubleTapIdentification.tag = 1;
break;
case 1:
[_unitViewForDoubleTapIdentification setHighlightedImage:self.box];
self->_unitViewForDoubleTapIdentification.tag = 0;
break;
default:
break;
}
}
and Here the singleTap
- (IBAction)unitSingleTapped:(id)sender {
[self dismissAllPopTipViews];
UIGestureRecognizer *gestureRecognizer = [UIGestureRecognizer alloc];
gestureRecognizer = (UIGestureRecognizer *)sender;
UIImageView *imageView = [[UIImageView alloc] init];
imageView = (UIImageView *)gestureRecognizer.view;
if (sender == _currentPopTipViewTarget) {
// Dismiss the popTipView and that is all
self.currentPopTipViewTarget = nil;
}
NSString *contentMessage = nil;
UIImageView *contentView = nil;
NSNumber *key = [NSNumber numberWithInt:imageView.tag];
id content = [self.contents objectForKey:key];
if ([content isKindOfClass:[NSString class]]) {
contentMessage = content;
}
else {
contentMessage = #"A large amount ot text in this bubble\najshdjashdkgsadfhadshgfhadsgfkasgfdasfdhasdkfgaodslfgkashjdfg\nsjfkasdfgkahdjsfghajdsfgjakdsfgjjakdsfjgjhaskdfjadsfgjdsfahsdafhjajdskfhadshfadsjfhadsjlfkaldsfhfldsa\ndsfgahdsfgajskdfgkafd";
}
NSArray *colorScheme = [_colorSchemes objectAtIndex:foo4random()*[_colorSchemes count]];
UIColor *backgroundColor = [colorScheme objectAtIndex:0];
UIColor *textColor = [colorScheme objectAtIndex:1];
CMPopTipView *popTipView;
if (contentView) {
popTipView = [[CMPopTipView alloc] initWithCustomView:contentView];
}
else {
popTipView = [[CMPopTipView alloc] initWithMessage:contentMessage];
}
[popTipView presentPointingAtView:imageView inView:self.view animated:YES];
popTipView.delegate = self;
popTipView.disableTapToDismiss = YES;
popTipView.preferredPointDirection = PointDirectionUp;
if (backgroundColor && ![backgroundColor isEqual:[NSNull null]]) {
popTipView.backgroundColor = backgroundColor;
}
if (textColor && ![textColor isEqual:[NSNull null]]) {
popTipView.textColor = textColor;
}
popTipView.animation = arc4random() % 2;
popTipView.has3DStyle = (BOOL)(arc4random() % 2);
popTipView.dismissTapAnywhere = YES;
[popTipView autoDismissAnimated:YES atTimeInterval:3.0];
[_visiblePopTipViews addObject:popTipView];
self.currentPopTipViewTarget = sender;
}
Hope you can help me, thanks in advance.
that's a lot of code to go through.. but I add more identifiers to UIViews (ie other than the tag identifier) by using obj-c runtime associative references..
So this is a category I attach to my UIView:
#import "UIView+Addons.h"
#import <objc/runtime.h>
#define kAnimationDuration 0.25f
#implementation UIView (Addons)
static char infoKey;
static char secondaryInfoKey;
-(id)info {
return objc_getAssociatedObject(self, &infoKey);
}
-(void)setInfo:(id)info {
objc_setAssociatedObject(self, &infoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(id)secondaryInfo {
return objc_getAssociatedObject(self, &secondaryInfoKey);
}
-(void)setSecondaryInfo:(id)info {
objc_setAssociatedObject(self, &secondaryInfoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#end
here is an example of my own code where I use the above to address a problem similar to the one you're facing:
if (![[view info] boolValue]) { // not selected?
self.moveToFolderNumber = [view secondaryInfo];
[view setInfo:#YES];
}

Zoom a UIScrollview on Objective-C

In one of the projects I'm working on, I have a UIScrollView that has a lot of buttons and labels that resemble movie theater seats that the user can tap to select seats for them to buy. Is it possible to zoom the UIScrollView? I have already declared the UIScrollViewDelegate, set the delegate to self, set the minimum and maximum zoom scale but I'm having issues with the viewForZoomingInScrollView and scrollViewDidEndZooming methods. I tried to return my scrollview on the viewForZoomingInScrollView method but it crashes.
Here's some of the code:
- (void) renderSeatMapOnScreen
{
int x_offset_row = 10;
int y_offset_row = 25;
int x_offset_col = 30;
int y_offset_col = 0;
int scrollview_w = 0;
int scrollview_h = 0;
NSString *row_name = #"";
int tag_index = 0;
NSMutableArray *seat_map_table = [seat_map_xml seats_map];
NSString *seat_available_str = [seat_avail_xml seat_available];
HideNetworkActivityIndicator();
NSLog(#"Seats available = %#", seat_available_str);
NSArray *seats_avail = [seat_available_str componentsSeparatedByString:#";"];
int ROW_COL_OFFSET = 25;
for (int row = 0; row < [seat_map_table count]; row++)
{
UILabel * rowlabel = [[UILabel alloc] init];
rowlabel.frame = CGRectMake(x_offset_row , y_offset_row, 22, 22);
SeatMapDeclaration *rowmap = [seat_map_table objectAtIndex:row];
rowlabel.text = rowmap.rows;
[scrollview addSubview:rowlabel];
row_name = [NSString stringWithFormat:#"%#", rowmap.rows];
NSArray *seat = [rowmap.rowmap componentsSeparatedByString:#";"];
NSLog(#"row[%i] = %#", row, rowmap.rowmap);
if (row == 0)
{
scrollview_w = [seat count] * ROW_COL_OFFSET + y_offset_row;
total_column = [seat count];
total_row = [seat_map_table count];
}
x_offset_col = 30 ;
y_offset_col = y_offset_row ;
for (int column = 0; column < [seat count]; column++)
{
if (([[seat objectAtIndex:column] rangeOfString:#"a("].location != NSNotFound)
|| ([[seat objectAtIndex:column] isEqualToString:#""]))
{
CGRect myImageRect = CGRectMake(x_offset_col, y_offset_col, 22, 22);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImageRect];
[imageView setImage:[UIImage imageNamed:#"noseat.png"]];
[scrollview addSubview:imageView];
}
else if ([[seat objectAtIndex:column] rangeOfString:#"b("].location != NSNotFound)
{
CGRect myImageRect = CGRectMake(x_offset_col, y_offset_col, 22, 22);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImageRect];
imageView.image = [UIImage imageNamed:#"noseat.png"];
[scrollview addSubview:imageView];
}
else
{
NSString *status = [NSString stringWithFormat:#"%#%#", row_name, [seat objectAtIndex:column]];
BOOL matchedFound = NO;
for (int i = 0; i < [seats_avail count]; i++)
{
if ([[seats_avail objectAtIndex:i] isEqualToString:status])
{
matchedFound = YES ;
break ;
}
}
if (matchedFound == YES)
{
UIButton * seat_btn = [UIButton buttonWithType:UIButtonTypeCustom];
[seat_btn setBackgroundImage:[UIImage imageNamed:#"seatavailable.png"] forState:UIControlStateNormal];
[seat_btn setBackgroundImage:[UIImage imageNamed:#"seatactive.png"] forState:UIControlStateSelected];
seat_btn.frame = CGRectMake(x_offset_col, y_offset_col, 22, 22);
tag_index = [[seat objectAtIndex:column] intValue];
[seat_btn setTitle:[seat objectAtIndex:column] forState:UIControlStateNormal];
seat_btn.titleLabel.font = [UIFont fontWithName:#"Helvetica" size:12.0];
seat_btn.tag = tag_index + row * 100;
[seat_btn addTarget:self
action:#selector(checkboxButton:)
forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:seat_btn];
}
else
{
CGRect myImageRect = CGRectMake(x_offset_col, y_offset_col, 22, 22);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImageRect];
imageView.image = [UIImage imageNamed:#"seat_not_available.png"];
[scrollview addSubview:imageView];
}
}
x_offset_col += ROW_COL_OFFSET ;
NSString *data = #"";
[seatControl addObject:data];
}
y_offset_row += ROW_COL_OFFSET;
}
UILabel *screenlabel = [[UILabel alloc] init];
screenlabel.frame = CGRectMake((scrollview_w-300)/2, 3, 300, 15);
screenlabel.text = #"Screen";
screenlabel.backgroundColor = [UIColor blackColor];
screenlabel.textColor = [UIColor whiteColor] ;
screenlabel.font = [UIFont fontWithName:#"Helvetica" size:10.0];
screenlabel.textAlignment = UITextAlignmentCenter;
[scrollview addSubview:screenlabel];
scrollview_h = y_offset_row + ROW_COL_OFFSET;
// Adjust scroll view
[scrollview setContentSize:CGSizeMake(scrollview_w, scrollview_h )];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
NSLog(#"1");
return scrollview;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
NSLog(#"2");
}
In:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
NSLog(#"1");
return scrollview;
}
you are not supposed to return the UIScrollView itself, rather its subview that you would like to scroll/zoom.
If you have many subviews, I would suggest creating a container view for all of them that you return from viewForZoomingInScrollView; instead of adding your seats to the scrollview itself you would then add them to the container view.
If you want to zoom to a certain seat in the UIScrollView, you should use zoomToRect: animated:. You can specify a certain rectangle (i.e. the seat) to which you would like to zoom in on.
Zooming only works when you implement the viewForZoomingInScrollView: delegate callback.
UIImageView *tempImage = [[UIImageView alloc]initWithImage:[UIImage imageWithData:data]];
self.imageView = tempImage;
scrollView.contentSize = CGSizeMake(imageView.frame.size.width , imageView.frame.size.height);
scrollView.maximumZoomScale = 1;
scrollView.minimumZoomScale = .37;
scrollView.clipsToBounds = YES;
scrollView.delegate = self;
[scrollView addSubview:imageView];
scrollView.zoomScale = .37;
-(UIView *) viewForZoomingInScrollView:(UIScrollView *)inScroll {
return imageView;
}

Multiple UITextfield Create Dynamically in iphone sdk

I have to create a multiple textfield dynamically on scrollview in ipad app. textfield created successfully and i use popup view on clicked textfield but when i clicked on textfield i dont get the Tag of Textfield. i get tag of last textfield so i cant set the text on the current textfield.
Following code i used...
int j = 430;
int k = 413;
int RB = 423;
for (int i=0; i<[appDelegate.questions count]; i++) {
imgTxtQue = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"textbox.png"]];
imgTxtQue.frame = CGRectMake(267, k, 490, 60);
// UIImageView *imgRatingBtn = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]];
// imgRatingBtn.frame = CGRectMake(633, RB, 102, 39);
//ratingButton1.hidden = NO;
ratingButton1 = [[UIButton alloc] initWithFrame:CGRectMake(633, RB, 102, 39)];
[ratingButton1 setImage:[UIImage imageNamed:#"rating_selected.png"] forState:UIControlStateNormal];
txtQuestions = [[UITextField alloc] initWithFrame:CGRectMake(296, j, 429, 24)];
//txtQuestions.tag = i;
[txtQuestions setTag:i];
NSLog(#"%d", txtQuestions.tag);
txtQuestions.delegate = self;
[txtQuestions setPlaceholder:[[appDelegate.questions objectAtIndex:i] objectForKey:#"question"]];
txtQuestions.borderStyle = UITextBorderStyleNone;
// txtQuestions.background = imgTxtQue.image;
[scrView addSubview:imgTxtQue];
[scrView addSubview:ratingButton1];
[scrView addSubview:txtQuestions];
j = j+50;
k = k+50;
RB = RB+50;
}
-(void)loadQuestion
{
txtQuestionOne.hidden=NO;
imgTxtQue.hidden=NO;
CGRect aFrame1 = imgTxtQue.frame;
aFrame1.size.width = aFrame1.size.width + 200;
// aFrame.size.height = newHeight;
NSString *strQue = [NSString stringWithFormat:#"%#",[[appDelegate.questions objectAtIndex:0] objectForKey:#"question"]];
CGSize newSize1 = [strQue sizeWithFont: [UIFont fontWithName: #"TrebuchetMS" size: 12] ];
if (strQue.length > 42) {
imgTxtQue.frame = CGRectMake(267, 413, newSize1.width+353, 60);
[txtQuestionOne setFrame:CGRectMake(294, 430, newSize1.width+350, 24)];
ratingButton1.frame = CGRectMake(855, 423, 102, 39);
ratingLabel1.frame = CGRectMake(900, 430, 42, 21);
}
[txtQuestionOne setPlaceholder:[[appDelegate.questions objectAtIndex:0] objectForKey:#"question"]];
appDelegate.dynamicQues =[[appDelegate.questions objectAtIndex:0] objectForKey:#"question"];
NSLog(#"current q1 %#", [[appDelegate.questions objectAtIndex:0] objectForKey:#"question"]);
if ([[[appDelegate.questions objectAtIndex:0] objectForKey:#"permission"] isEqualToString:#"1"]) {
ratingButton1.hidden=NO;
ratingLabel1.hidden=NO;
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
BOOL editing=YES;
for (UIImageView *img in ViewPost.subviews)
{
if ([img isKindOfClass:[UIImageView class]])
{
if (img.tag==textField.tag)
{
[img setImage:[UIImage imageNamed:#"Redtextbox.png"]];;
}
else{
if (img.tag!=0) {
if (img.tag != 10) {
[img setImage:[UIImage imageNamed:#"textbox.png"]];
}
else
{
[img setImage:[UIImage imageNamed:#"inputbox.png"]];
}
}
}
}
}
if (textField==txtcategory) {
[textField resignFirstResponder];
appDelegate.category=YES;
editing=NO;
touchflag=1;
[self performSelectorOnMainThread:#selector(CategoryListClick) withObject:nil waitUntilDone:YES];
//[self CategoryListClick];
return NO;
}
if (textField==txtsubcategory) {
appDelegate.category=NO;
editing=NO;
[self performSelectorOnMainThread:#selector(CategoryListClick) withObject:nil waitUntilDone:YES];
}
if (txtQuestions.tag) {
// if (textField==txtQuestions) {
editing=NO;
index=txtQuestions.tag;
NSLog(#"%d",txtQuestions.tag);
touchflag = 1;
[self performSelectorOnMainThread:#selector(loadAnswers) withObject:nil waitUntilDone:YES];
// }
}
-(void)loadAnswers{
if (touchflag==1) {
[Name resignFirstResponder];
[Email resignFirstResponder];
[txtCityCode resignFirstResponder];
[txtcategory resignFirstResponder];
[txtTitle resignFirstResponder];
[txtQuestions resignFirstResponder];
[txtsubcategory resignFirstResponder];
SubcategoryPopViewController *objPopview = [[SubcategoryPopViewController alloc]initWithNibName:#"SubcategoryPopViewController" bundle:nil];
objPopview.delegate = self;
objPopview.index=txtQuestions.tag;
popView =[[UIPopoverController alloc]initWithContentViewController:objPopview];
[self RescheduleTimer];
[popView presentPopoverFromRect:imgTxtQue.frame inView:ViewPost permittedArrowDirections:0 animated:NO];
[popView setPopoverContentSize:CGSizeMake(376, 260)];
}
}
-(void) didSelectAnswer{
touchflag=0;
[popView dismissPopoverAnimated:YES];
[self RescheduleTimer];
if (appDelegate.ansDynamic==YES) {
// txtQuestionOne.text=appDelegate.answerOne;
if (txtQuestions.tag) {
txtQuestions.text = appDelegate.answerDynamic;
}
appDelegate.ansDynamic=NO;
questionIndex=txtQuestions.tag;
if (![ratingButton1 isHidden]) {
ratingButton1.enabled=YES;
RatingPopViewController *objPopview = [[RatingPopViewController alloc]initWithNibName:#"RatingPopViewController" bundle:nil];
objPopview.index=txtQuestions.tag;
objPopview.checkedCell=ratingLabel1.text;
objPopview.QuestionText=appDelegate.answerDynamic;
objPopview.delegate=self;
popSweepStakes =[[UIPopoverController alloc]initWithContentViewController:objPopview];
[popSweepStakes presentPopoverFromRect:ratingButton1.frame inView:ViewPost permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
[popSweepStakes setPopoverContentSize:CGSizeMake(300, 400)];
}
return;
}
In the above code i get the tag correctly but when i use tag on other mathod then i only get the last textfields tag.
Thanks,
Rahul Virja
You overwrite txtQuestions variable.
Declare a class attribute like this NSMutableArray * _textFieldArray. (It's import declare a NSMutableArray object for add your textField).
In the init method of your class allocate and init your array: _textFieldArray = [[NSmutableArray alloc]init].
In your for statement use the following code for allocate a textField:
UItextField * txtQuestions = [[UITextField alloc] initWithFrame:CGRectMake(296, j, 429, 24)];
After setting all your property on txtQuestions object, add it to the array
[_textFieldArray addObject:txtQuestions]
When you need for a textfield use this code:
[_textFieldArray objectAtIndex:txtQuestions.tag]
Is it Clear?

Memory Leak adding Subview in iPhone?

I am trying to add a subview on ImageView control, I think, i have alloc view and dealloc view properly.This is my code.
for(int Count =0; Count < [list count]; Count++)
{
MapCallout *callout = [list objectAtIndex:Count];
CGSize constSize = { 700.0f, 40.0f };
NSString * sTmp = [callout.Name stringByAppendingString:#"WW"];
CGSize textSize = [sTmp sizeWithFont:[UIFont fontWithName:#"Arial-BoldMT" size:25.0] constrainedToSize:constSize lineBreakMode:UILineBreakModeClip];
int xValue = callout.X;
int yValue = callout.Y;
int position = 0;
UIImage *calloutImage;
if(callout.Direction==0)
{
calloutImage=[UIImage newImageFromResource:#"arrow-0.png"];
callout.Y=callout.Y-3; position= -3;
}
else if(callout.Direction==1)
{
calloutImage=[UIImage newImageFromResource:#"arrow-1.png"];
callout.Y=callout.Y-3; position= -3;
}
else if(callout.Direction==2)
{
callout.Y=callout.Y + 2;
calloutImage=[UIImage newImageFromResource:#"arrow_2.png"];
position= +2;
}
CalloutButton *calloutButton = nil;
int arraySize = [dequeueReusableCallout count] - 1;
if(Count > arraySize)
{
calloutButton = [[[CalloutButton alloc]initWithFrame:CGRectMake(xValue,
self.tapDetectingImageView.frame.origin.y + yValue ,
textSize.width,40)] autorelease];
[calloutButton setDelegate:self];
[dequeueReusableCallout addObject:calloutButton];
}
calloutButton = [dequeueReusableCallout objectAtIndex:Count];
[calloutButton setFrame:CGRectMake(xValue,
self.tapDetectingImageView.frame.origin.y + yValue ,
textSize.width,40)] ;
[calloutButton setBackgroundImage:calloutImage andText:callout.Name andYvalue:position];
calloutButton.tag = callout.ID;
calloutButton.ViewMapType = [callout.calloutType intValue];
calloutButton.isLive = callout.isLive;
calloutButton.isAnimated = callout.isAnimated;
[self.tapDetectingImageView addSubview:calloutButton];
}
//Callout Button Method
-(void) setBackgroundImage:(UIImage*)image andText:(NSString*)text andYvalue:(double)Y
{
if(!btnCallout)
btnCallout = [[UIButton alloc] init];
[btnCallout setFrame:CGRectMake(0, -Y, self.frame.size.width, self.frame.size.height)];
[btnCallout setBackgroundImage:image forState:UIControlStateNormal];
[btnCallout addTarget:self action:#selector(CalloutTouch:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btnCallout];
if(!lblCallout)
lblCallout = [[UILabel alloc] init];
[lblCallout setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
lblCallout.backgroundColor = [UIColor clearColor];
lblCallout.font = [UIFont systemFontOfSize:42.0];
lblCallout.userInteractionEnabled = NO;
lblCallout.text = text;
lblCallout.textAlignment = UITextAlignmentCenter;
lblCallout.font = [UIFont fontWithName:#"Arial-BoldMT" size:25.0];
[self addSubview:lblCallout];
}
[self viewForZoomingInScrollView:self.mapScrollView];
}
If i call this method method multi-times, memory warning is occur and app get crash.
Here, [self.tapDetectingImageView addSubview:calloutButton]; I if comment this statement, it is working properly. Please let me know where i am wrong.
You should call [calloutButton release] after you add it to the dequeueReusableCallout array since the array now has a retain on the newly allocated instance

How to remove subviews from superviews and redraw on a click a button click?

How to remove subviews from superviews and redraw on a click a button click?
float padding = 5.0;
float view_width = 95.0;
float view_height = 120.0;
int rows = 0.0f;
int columns = 0.0f;
UIView *myAddedView ;
for (int i=0; i<[product.CorrentAnswer intValue]; i++)
{
if(i%3 == 0 && i > 0)
{
columns = 0.0f;
rows += view_height;
}
myAddedView =[[[UIView alloc] initWithFrame:CGRectMake(padding+columns, rows, view_width, view_height)] autorelease];
myAddedView.backgroundColor = [UIColor clearColor];
CGRect myImageRect = CGRectMake( 40, 100.0f, 40.0f, 40.0f);
UIImageView *myImage = [[UIImageView alloc]initWithFrame:myImageRect];
NSString *imageName = [NSString stringWithFormat:#"%#",product.imagename];
[myImage setImage:[UIImage imageNamed:imageName]];
[myAddedView addSubview:myImage];
[viewarray addObject:myAddedView];
[self.view addSubview:myAddedView];
columns+= view_width;
}
i want to remove myAddedView from self.view?
hope to get answer very soon....
you can do this by assigning a tag to myAddedView ....
code change :
myAddedView =[[[UIView alloc] initWithFrame:CGRectMake(padding+columns, rows, view_width, view_height)] autorelease];
myAddedView.backgroundColor = [UIColor clearColor];
//add this line
myAddedView.tag = 10;
and on the button click(when you want to remove the subview) write :
if([self.view viewWithTag:10]!=nil)
{
[[self.view viewWithTag:10] removeFromSuperView];
}
thanks
the answer from user698952 is okay, adding a tag is the way to go.
myAddedView.tag = 10;
If you have more than one view with the same tag you have to change the code for removal a little bit.
UIView *someView = nil;
while (someView = [self.view viewWithTag:10]) {
[someView removeFromSuperview];
}