I have a class that implements "UIView" and inside - (void)drawRect:(CGRect)rect method I add some custom buttons to self. Inside a UIViewController I declare an instance of this view and i add it to self.view.
If i do this in - (void)viewDidLoad, everything works perfect, but if I create a method that is called when I push a button, and add that view to self.view, the buttons background is displayed after a few second. Till then only the name of the button appears written in white.
What do i do wrong?
Regards
#implementation CustomButton
#synthesize isPressed, buttonViewNumber;
- (id)initWithFrame:(CGRect)frame
title:(NSString *)title
tag:(int)tag
{
self = [super initWithFrame:frame];
if (self) {
[self setTitle:title forState:UIControlStateNormal];
[self setTag:tag];
self.titleLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
self.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self setBackgroundImage:[[UIImage imageNamed:#"btn_white_add.png"] stretchableImageWithLeftCapWidth:20.0 topCapHeight:0.0] forState:UIControlStateNormal];
[self addTarget:self action:#selector(didSelect) forControlEvents:UIControlEventTouchUpInside];
self.isPressed = NO;
}
return self;
}
#implementation ButtonsView
#synthesize listOfButtons;
- (id)initWithFrame:(CGRect)frame bundle:(NSArray *)data
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
listOfNames = [[NSArray arrayWithArray:data] retain];
listOfButtons = [[NSMutableArray alloc] init];
currentViewNumber = 0;
viewNumber = 0;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGSize maximumLabelSize = CGSizeMake(300,24);
UIFont *buttonFont = [UIFont fontWithName:#"Helvetica" size:14.0];
float lineSize = 0;
float lineNumber = 0;
NSArray *listOfFrameX = [NSArray arrayWithObjects:
[NSString stringWithFormat:#"%d",FIRST_LINE_Y],
[NSString stringWithFormat:#"%d",SECOND_LINE_Y],
[NSString stringWithFormat:#"%d",THIRD_LINE_Y],
nil];
for (int i = 0; i < [listOfNames count]; i++) {
CGSize expectedLabelSize = [[[listOfNames objectAtIndex:i] objectForKey:#"name"] sizeWithFont:buttonFont
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeTailTruncation];
if ((lineSize + expectedLabelSize.width) > 260) {
lineNumber++;
lineSize = 0;
}
if (lineNumber > 2) {
viewNumber ++;
lineSize = 0;
lineNumber = 0;
}
CGRect newFrame = CGRectMake(lineSize,
[[listOfFrameX objectAtIndex:lineNumber] floatValue],
expectedLabelSize.width+30,
24);
CustomButton *myButton = [[CustomButton alloc] initWithFrame:newFrame
title:[[listOfNames objectAtIndex:i] objectForKey:#"name"]
tag:[[[listOfNames objectAtIndex:i] objectForKey:#"id"] intValue]];
myButton.buttonViewNumber = viewNumber;
[listOfButtons addObject:myButton];
if (viewNumber == 0) {
[self addSubview:myButton];
}
lineSize += expectedLabelSize.width + 40;
[myButton release];
}
}
this way it works:
- (void)viewDidLoad
{
[super viewDidLoad];
placeholders = [[NSArray arrayWithObjects:
something,something, something,something,nil] retain];
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:placeholders];
[self.view addSubview:buttonsView];
and like this is doesnt work:
- (void)getCompanyNames:(id)result
{
NSArray *listOfCompanies = (NSArray *)result;
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:listOfCompanies];
[self.view addSubview:buttonsView];
}
i need to add the "buttonsView" object to self.view after the -viewDidLoad
drawRect: isn't exactly the place you should be creating subviews (Buttons are subviews) for your view. This should either go into initWithFrame: or awakeFromNib, depending on your view creation method: programmatically or using a nib.
Related
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];
}
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;
}
I am trying to make a survey app but I can't make the memory management although I am using ARC. My app makes memory leak. I get memory warning. When I make my app in interface builder statically there is no problem but when i make my app programmatically I get memory problem. Why is that happening? Here is my code:
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
int soruAdedi = 20;
#interface ViewController ()
#end
#implementation ViewController
#synthesize scrollView2;
-(void)textViewBicimle: (UITextField *)textAlani{
[textAlani.layer setBorderColor:[[[UIColor blackColor] colorWithAlphaComponent:1.0] CGColor]];
[textAlani.layer setBorderWidth:1.0];
}
- (void) tableCiz:(NSMutableArray *)hucreler sutun:(int)sutunSayisi satir:(int)satirSayisi{
int z = 0;
for (int i =0;i<satirSayisi;i++){
for(int j=0;j<sutunSayisi&&z<satirSayisi*sutunSayisi;j++,z++){
[self textViewBicimle:[hucreler objectAtIndex:z]];
[[hucreler objectAtIndex:z] setFrame:CGRectMake((20+j*100), (20+i*40), 100, 40)];
}
}
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
}
-(void)hucreArrayOlustur: (int)sutunSayisi suankiView:(UIView *)soruViewIki satir:(int)satirSayisi{
for (int i = 0; i <sutunSayisi*satirSayisi; i++){
textView = [[UITextField alloc]init];
textView.text = #"dsgfdh";
[hucreArray addObject:textView];
[soruViewIki addSubview:textView];
}
}
-(void)viewOlustur{
for (int i = 0; i <soruAdedi; i++){
hucreArray = [[NSMutableArray alloc]init];
if (i == 0){
soruView = [[UIView alloc]initWithFrame:CGRectMake(20, 20, 728, 0)];
soruView.clipsToBounds = YES;
soruView.backgroundColor = [UIColor lightGrayColor];
[self hucreArrayOlustur:5 suankiView:soruView satir:10];
[self tableCiz:hucreArray sutun:5 satir:10];
CGRect frame = soruView.frame;
CGRect frame2 = [[hucreArray objectAtIndex:49] frame];
frame.size.height = frame2.origin.y+frame2.size.height+34;
soruView.frame = frame;
[viewArray addObject:soruView];
[scrollView2 addSubview:soruView];
}
else{
CGRect frameGecici = [[viewArray objectAtIndex:i-1] frame];
float geciciY = frameGecici.origin.y+frameGecici.size.height+1;
soruView = [[UIView alloc]initWithFrame:CGRectMake(20, geciciY, 728, 0)];
soruView.clipsToBounds = YES;
soruView.backgroundColor = [UIColor lightGrayColor];
[self hucreArrayOlustur:5 suankiView:soruView satir:10];
[self tableCiz:hucreArray sutun:5 satir:10];
CGRect frame = soruView.frame;
CGRect frame2 = [[hucreArray objectAtIndex:49] frame];
frame.size.height = frame2.origin.y+frame2.size.height+34;
soruView.frame = frame;
[viewArray addObject:soruView];
[scrollView2 addSubview:soruView];
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
scrollView2.delegate = self;
scrollView2.contentSize = CGSizeMake(0, 8000);
viewArray = [[NSMutableArray alloc]init];
[self viewOlustur];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[self setScrollView2:nil];
[super viewDidUnload];
}
#end
I have a viewcontroller(mainViewController) and view class(UIView class, mainView). mainViewController, I called a method "generateView" from mainView class. Here is the code:
Method 1:
- (void) generateView {
container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
container.backgroundColor = [UIColor clearColor];
container.contentSize = CGSizeMake(500,1200);
container.showsVerticalScrollIndicator = YES;
[container setScrollEnabled:TRUE];
container.backgroundColor = [UIColor redColor];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/images/items/%i.png", HOSTADDR, i ]]];
[b setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:self action:#selector(testFunction:) forControlEvents:UIControlEventTouchUpInside];
[b setEnabled:TRUE];
[b setUserInteractionEnabled:TRUE];
[container addSubview:b];
col++;
}
[self addSubview:container];
}
- (void) testFunction: (id) sender {
NSLog(#"Function called. Sender tag number: %i", [sender tag]);
}
Method 2:
- (void) generateView {
container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
container.backgroundColor = [UIColor clearColor];
container.contentSize = CGSizeMake(500,1200);
container.showsVerticalScrollIndicator = YES;
[container setScrollEnabled:TRUE];
container.backgroundColor = [UIColor redColor];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/images/items/%i.png", HOSTADDR, i ]]];
[b setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:mainViewController action:#selector(updateData:) forControlEvents:UIControlEventTouchUpInside];
[b setEnabled:TRUE];
[b setUserInteractionEnabled:TRUE];
[container addSubview:b];
col++;
}
[self addSubview:container];
}
What I really need is method 2, cuz I want to call the updateData in mainViewController, but no matter how i tried, the button is not calling the function thats supposed to be called. Any idea?
EDIT:
This is how I called the view class
- (void) loadContent: (id) sender {
[self removeSubmenus];
switch ([sender tag]) {
case 2001:
{
MainView *mainView = [[MainView alloc] initWithSubmenu:CGRectMake(420, 85, 0, 0)];
[self.view addSubview:mainView];
break;
}
default:
break;
}
}
You should set delaysContentTouches to YES on the UIScrollView.
You're also leaking a bunch of memory. Make sure you're releasing both the UIButton (b) and NSData (imageData) objects as soon as you're done with them.
--
EDIT: I tried your code and it works fine. But it seems you wanted all this code in a UIView, so I threw together a quick sample.
TestView.h
#import <UIKit/UIKit.h>
#interface TestView : UIView {}
#end
TestView.m
#import "TestView.h"
#implementation TestView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIScrollView *container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:self action:#selector(testFunction:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:b];
[b release];
col++;
}
[self addSubview:container];
}
return self;
}
- (void) testFunction: (id) sender {
NSLog(#"Function called. Sender tag number: %i", [sender tag]);
}
- (void)dealloc {
[super dealloc];
}
#end
TestController.h
#interface TestController : UIViewController { }
#end
TestController.m:
#import "TestController.h"
#import "TestView.h"
#implementation TestController
- (void) generateView {
TestView *tv = [[TestView alloc]initWithFrame:[self.view frame]];
[self.view addSubview:tv];
[tv release];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self generateView];
}
- (void)dealloc {
[super dealloc];
}
#end
Try adding this code to your method
container.delaysContentTouches = NO;
container.canCancelContentTouches = NO;
Pls modify your code to avoid memory leaks. Make sure you delete objects that you take ownership of.
Try this,
[b addTarget:mainViewController.view action:#selector(updateData:) forControlEvents:UIControlEventTouchUpInside];
How does one create a dynamic thumbnail grid?
How is a grid created with thumbnails of images like the photo app on iphone?
How are these spaces arranged dynamically? e.g. adding and removing thumbnails.
this is my simple grid view app
- (void)viewDidAppear:(BOOL)animated {
[[Grid_ViewAppDelegate sharedAppDelegate] hideLoadingView];
temp = temp+1;
if (temp ==1){
NSLog(#"temp:%d",temp);
int n = 20; //Numbers of array;
NSArray *t = [[NSArray alloc] initWithObjects:#"calpie.gif",#"chrysler_electric.png",#"chrysler_fiat_cap.gif",#"cleanup.gif",#"ecylindri.gif",#"elect08.png",#"globe.gif",#"heat.gif",#"insur.gif"
,#"jobs.gif",#"office.gif",#"opec1.gif",#"orng_cap.gif",#"poll.gif",#"pollen.gif",#"purbar.gif",#"robinson.gif",#"robslink_cap.gif",#"scot_cap.gif",#"shoes.gif",nil];
myScrollView.contentSize = CGSizeMake(320, 460+n*2);
myScrollView.maximumZoomScale = 4.0;
myScrollView.minimumZoomScale = 1;
myScrollView.clipsToBounds = YES;
myScrollView.delegate = self;
NSString *mxiURL = #"http://meta-x.com/biflash/images/";
int i =0,i1=0;
while(i<n){
int yy = 4 +i1*79;
for(int j=0; j<4;j++){
if (i>=n) break;
CGRect rect;
rect = CGRectMake(4+79*j, yy, 75, 75);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
NSString *nn = [mxiURL stringByAppendingString:[t objectAtIndex:i]];
UIImage *buttonImageNormal=[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: nn]]];
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
button.tag =i;
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside ];
//[self.view addSubview:button];
[myScrollView addSubview:button];
//[buttonImageNormal release];
[button release];
i++;
//
}
i1 = i1+1;
//i=i+4;
}
}
}
in AppDelegate
+ (Grid_ViewAppDelegate *)sharedAppDelegate
{
return (Grid_ViewAppDelegate *)[UIApplication sharedApplication].delegate;
}
- (void)showLoadingView
{
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor grayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(142.0, 222.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
CGRect label = CGRectMake(142.0f, 255.0f, 71.0f, 20.0f);
lblLoading = [[UILabel alloc] initWithFrame:label];
lblLoading.textColor = [UIColor whiteColor];
lblLoading.font = [UIFont boldSystemFontOfSize:14];
// UILabel
lblLoading.backgroundColor =[UIColor clearColor];
[lblLoading setText:#"Loading..."];
//[lblLoading setTextAlignment:UITextAlignmentCenter];
[loadingView addSubview:lblLoading];
}
[window addSubview:loadingView];
}
- (void)hideLoadingView
{
[loadingView removeFromSuperview];
}
definitely if u apply this logic. u get succeed