Custom search results button has weird behaviour in UISearchBar - iphone

I subclassed UISearchBar in order to set custom image to search results button the following way (.m file):
#import "CustomUISearchBar.h"
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#implementation GipUISearchBar
- (void)layoutSubviews
{
UITextField *searchField = nil;
UIView *backGround = nil;
UIButton *cancelButton = nil;
NSUInteger numViews = [self.subviews count];
for(int i = 0; i < numViews; i++)
{
if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
{
searchField = [self.subviews objectAtIndex:i];
}
else if ([[self.subviews objectAtIndex:i] isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
backGround = [self.subviews objectAtIndex:i];
}
else if ([[self.subviews objectAtIndex:i] isKindOfClass:[UIButton class]])
{
cancelButton = [self.subviews objectAtIndex:i]; [cancelButton setTintColor:RGB(22.0,38.0,111.0)];
}
}
if(!(searchField == nil))
{
searchField.layer.cornerRadius=15.0f;
searchField.layer.masksToBounds=YES;
searchField.layer.borderColor = [RGB(26.0,141.0,223.0)CGColor];
searchField.layer.borderWidth = 2.0f;
UIImage *glassImage = [UIImage imageNamed: #"search_icon.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:glassImage];
searchField.leftView = iView;
[iView release];
UIImage *historyImage = [UIImage imageNamed:#"history_button.png"];
UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[historyButton setBackgroundImage:historyImage forState:UIControlStateNormal];
[historyButton setBackgroundImage:historyImage forState:UIControlStateSelected];
[historyButton setBackgroundImage:historyImage forState:UIControlStateDisabled];
[historyButton setBackgroundImage:historyImage forState:UIControlStateHighlighted];
historyButton.frame = CGRectMake(0,
0,
historyImage.size.width-3,
historyImage.size.height-3);
historyButton.layer.borderColor = [RGBA(0.0,0.0,0.0,0.0)CGColor];
historyButton.layer.borderWidth = 0.0f;
searchField.rightView = historyButton;
}
if (!(backGround == nil))
[backGround removeFromSuperview];
[super layoutSubviews];
}
The problem is when i touch inside search bar and it resizes i see this button being moved from left to right. How can i disable this behaviour?

try commenting below lines.
[super layoutSubviews];
Because it seems that you are overriding layout of UISearchBar by inheriting it.

Related

Change frame of cancel button in UISearchBar

I have the following code to change the appearance of the UISearchBar in my application and it can be seen in the image below also:
for(int i = 0; i < [[searchBar subviews] count]; i++){
UIView *subView = [[searchBar subviews] objectAtIndex:i];
if([[NSString stringWithFormat:#"%#", [subView class]] isEqualToString:#"UINavigationButton"]){
UIButton *cancelButton = (UIButton *)subView;
CGRect buttonFrame = cancelButton.frame;
buttonFrame.size.height = 52;
[cancelButton setFrame:buttonFrame];
[cancelButton setTitle:#"Cancel" forState:UIControlStateNormal];
[cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel_pressed.png"] forState:UIControlStateHighlighted];
}
}
As you can see I am trying to change the height of the button contained in the UISearchBar with no luck. I do get reference to the button as I can change the text and the background Image is changed just not the height of the frame. I would just like the height of the button to be the same as the search box at 52px.
EDIT:
I have found a really hacky solution, but it's not very elegant of adding a UIButton as the subview of the Cancel Button. It does the job but as I say it's not very nice.
Actually you could use method below to access the cancel Button:
UIBarButtonItem *cancelButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
So I override -layoutSubViews with this, but theres 2 issues I have
I hate iterating through the views to find the matching view, and it messes up the animation a little bit
- (UIButton *)cancelButton {
for (UIView *v in self.subviews) {
if ([v isKindOfClass:[UIButton class]]) {
NSString *caption = [[((UIButton *)v) titleLabel] text];
if ([caption isEqualToString:#"Cancel"] )
return (UIButton *)v;
}
}
return nil;
}
- (BOOL)cancelButtonIsShowing {
return ([self cancelButton] != nil);
}
- (void)layoutSubviews {
[super layoutSubviews];
if ([self cancelButtonIsShowing]) {
UIButton *cancelButton = [self cancelButton];
UIImage *i = [UIImage imageNamed:#"Cancel_BTN"];
CGRect f = CGRectMake(267, 5, i.size.width, i.size.height);
cancelButton.frame = f;
}
}

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

Dynamic assignment of random images as button's background separately

-(void)setButtons_AsPerTheMatrixSelection
{
for(UIView *subview in [viewWithButtons subviews])
{
if ([subview isKindOfClass:[UIButton class]])
{
[subview removeFromSuperview];
}
}
viewWithButtons = [[UIView alloc] init];
width = 48;
height = 48;
pw = 49;
ph = 49;
arrButton = [[NSMutableArray alloc] init];
UIImage *imgDefaultBG = [UIImage imageNamed:#"bg.jpg"];
viewWithButtons.frame = CGRectMake(50, 40, 200, 260);
ch = 4;
cv = 4;
for ( i = 0 ; i < cv ; ++i )
{
for ( j = 0 ; j < ch ; ++j )
{
btnMatrix = [[[UIButton alloc] initWithFrame:CGRectMake(10+pw*j, 51+ph*i, width, height)] autorelease];
btnMatrix.tag = i*ch+j;
btnMatrix.userInteractionEnabled = TRUE;
bulImageStatus = FALSE;
[btnMatrix addTarget:self action:#selector(changeImage:) forControlEvents:UIControlEventTouchDown];
[btnMatrix setBackgroundImage:imgDefaultBG forState:UIControlStateNormal];
[viewWithButtons addSubview:btnMatrix];
[arrButton addObject:btnMatrix];
}
}
NSLog(#"arrButton object count is:--> %d",[arrButton count]);
[self.view addSubview:viewWithButtons];
}
-(void)AddImageToArray
{
arr_FirstSet = [[NSMutableArray alloc] init];
NSString *strImageName;
if(appDelegate.intCategoryBtnTag == 0)
{
for (intimg = 1; intimg <= 28; intimg++)
{
strImageName = [NSString stringWithFormat:#"%d_1.png",intimg];
NSLog(#"strImageName is :--> %#",strImageName);
[arr_FirstSet addObject:strImageName];
}
NSLog(#"arr_FirstSet objects are...%#",arr_FirstSet);
}
}
-(void)changeImage:(id)sender
{
UIImage *img;
NSString *strImageName;
strImageName = [arr_FirstSet objectAtIndex:arc4random() % [arr_FirstSet count]/2];
NSLog(#"btnMatrix is:--> %#",strImageName);
img = [UIImage imageNamed:strImageName];
//[btnMatrix setImage:img forState:UIControlEventTouchDown];
NSLog(#"sender detail is:--> %#",sender);
[sender setBackgroundImage:img forState:UIControlStateHighlighted];
}
This is my code to set the dynamic buttons in "setButtons_AsPerTheMatrixSelection" method,
"AddImageToArray" method is used to add images from bundle to NSMutableArray (arr_FirstSet) one by one.
"changeImage" method is used to set the background of particular button.
I am able to set the images as background to the buttons randomly,
But the main problem is that i have to set fixed dynamic image to particular button.
right now on each click of particular button i am getting changed random image when i press it once, twice, thrice etc...
I have to set any particular image which is generated randomly in the "changeImage" to single button & rest to the other buttons single-single.
Then i have to check if two buttons have same background then these two buttons will be removed from the matrix.
Please guide me for the mistake i am doing & help me.
//Please replace this method
-(void)changeImage:(UIButton *)sender
{
UIImage *img;
NSString *strImageName;
strImageName = [arr_FirstSet objectAtIndex:arc4random() % [arr_FirstSet count]/2];
img = [UIImage imageNamed:strImageName];
//for the first time sender.imageView.image property will be null then only we set image to the button.
//For second click this condition fails and does not set the other image.
if(!sender.imageView.image)
{
[sender setImage:img forState:UIControlStateHighlighted];
[sender setImage:img forState:UIControlStateSelected];
}
// Calling a method to check if two images of buttons are same.
[self checkIfTwoImagesAreSame:sender];
}
//And Add this method
- (void)checkIfTwoImagesAreSameImageMaching:(UIButton *)sender
{
for(UIView *subview in [viewWithButtons subviews])
{
if ([subview isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)subview;
// This condition is comparing clicked button image with all the buttons images of the viewWithButtons view if it isEqual:
if(sender.imageView.image && btn.imageView.image && [sender.imageView.image isEqual:btn.imageView.image])
{
// this is checking if the clicked button is not comparing with itself
if(btn.tag != sender.tag)
{
[btn removeFromSuperview];
[sender removeFromSuperview];
// OR
// btn.selected = YES;
// sender.selected = YES;
// OR
// btn.hidden = YES;
// sender.hidden = YES;
}
}
}
}
}

Background image not displayed on UIView

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.

UIButton failed to call functions?

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