i have read about UITouch and UIGestureRecognizer, but i still really confused what the difference between them.
I have one case. In my app, i have a barbuttonitem, i want to show different view when a tap that button. if i do a singletap, i want to show a textview, but when i do a singletap again, i want to show a popover from that button. is there somebody can give me an example code to do it and give a little explanation about what is the difference between UITouch and UIGestureRecognizer???
UPDATE
the barbuttonitem is a wrapper of UISegmentedControl, here's a pic from the desain
i was try to use touchesBegan:withEvent: and touchesEnded:withEvent: to solve this problem, but i dont know how to connect it to that barbuttonitem.
This is the code i made :
-(void)addSegment{
NSAutoreleasePool *pool;
int count_doc = [_docsegmentmodels count];
NSLog(#"count doc add segment : %d", count_doc);
pool = [[NSAutoreleasePool alloc] init];
DocSegmentedModel *sl;
NSMutableArray *segmentTextMutable = [NSMutableArray array];
for(int i=0 ;(i<count_doc && i < max_segment);i++){
sl = [_docsegmentmodels objectAtIndex:i];
NSString *evalString = [[KoderAppDelegate sharedAppDelegate] setStringWithLength:sl.docSegmentFileName:10];
[segmentTextMutable addObject:NSLocalizedString(evalString,#"")];
}
NSArray *segmentText = [segmentTextMutable copy];
_docSegmentedControl = [[UISegmentedControl alloc] initWithItems:segmentText];
_docSegmentedControl.selectedSegmentIndex = 0;
_docSegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleHeight;
_docSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;//UISegmentedControlStylePlain;// UISegmentedControlStyleBar;//UISegmentedControlStyleBezeled;
//docSegmentedControl.frame = CGRectMake(0, 0, 800, 46.0);
[_docSegmentedControl addTarget:self action:#selector(docSegmentAction:) forControlEvents:UIControlEventValueChanged];
// Add the control to the navigation bar
//UIBarButtonItem *segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
segmentItem = [[UIBarButtonItem alloc] initWithCustomView:_docSegmentedControl];
self.navItem.leftBarButtonItem = segmentItem;
self.navItem.leftBarButtonItem.title = #"";
[pool release];
[segmentItem release];
[_docSegmentedControl release];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:#selector(segmentItemTapped:) object:segmentItem];
}
-(void)touchesEnd:(NSSet *)touches withEvent:(UIEvent *)event{
if (touches.count == 1) {
if (theTouch.tapCount == 2) {
[self performSelector:#selector(segmentItemTapped:)withObject:segmentItem afterDelay:0.35];
}else {
[self performSelector:#selector(docSegmentAction:) withObject:segmentItem afterDelay:0.0];
}
}
}
- (IBAction)segmentItemTapped:(id)sender{
if (self.fileProperties == nil) {
self.fileProperties = [[[FilePropertiesViewController alloc] initWithNibName:#"FilePropertiesViewController" bundle:nil]autorelease];
fileProperties.delegate = self;
self.filePropertiesPopover = [[[UIPopoverController alloc] initWithContentViewController:fileProperties]autorelease];
[_docsegmentmodels objectAtIndex:_docSegmentedControl.selectedSegmentIndex];
}
fileProperties.docProperties = _docsegmentmodels;
fileProperties.index = _docSegmentedControl.selectedSegmentIndex; //index utk nilai2 di textfield
[self.filePropertiesPopover presentPopoverFromBarButtonItem:sender
permittedArrowDirections:UIPopoverArrowDirectionUp
animated:YES];
}
- (IBAction)docSegmentAction:(id)sender{
NSLog(#"open file");
isFileOpen = YES;
[self.moreFilePopOverController dismissPopoverAnimated:YES];
[self.filePropertiesPopover dismissPopoverAnimated:YES];
[self showTextView];
}
is there any mistake in my understanding?
In your case you don't need UIGestureRecognizer. Simply set the action of the barbuttonitem to the method that should be called when the button is tapped. Have the method keep track of the state of the textview and depending on it show it or show the popover.
Related
Here's my GameViewController.m file:
- (void)viewDidLoad {
[super viewLoad];
.
.
.
_board = [[TwinstonesBoardModel alloc] init];
[_board setToInitialStateMain];
TwinstonesStoneView* twinstonesBoard = [[TwinstonesStoneView alloc]
initWithMainFrame:CGRectMake(12, 160, 301.5, 302.5)
andBoard:_board];
[self.view addSubview:twinstonesBoard];
TwinstonesStonesView *stoneOne = [[TwinstonesStoneView alloc] init];
TwinstonesStonesView *one = (TwinstonesStoneView*)stoneOne.stoneUnoView;
TwinstonesStonesView *stoneTwo = [[TwinstonesStoneView alloc] init];
TwinstonesStonesView *two = (TwinstonesStoneView*)stoneTwo.stoneDueView;
UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[one addGestureRecognizer:swipeLeft];
[two addGestureRecognizer:swipeLeft];
Here's the relevant code in my TwinstonesStoneView.m file:
#implementation TwinstonesStoneView
{
NSMutableArray* _array;
NSMutableArray* _emptyArray;
CGRect _frame;
NSUInteger _column;
NSUInteger _row;
TwinstonesBoardModel* _board;
int _i;
}
- (id)initWithMainFrame:(CGRect)frame andBoard:
(TwinstonesBoardModel*)board
{
if (Self = [super initWithFrame:frame])
{
float rowHeight = 49.0;
float columnWidth = 49.0;
float barrierHorizontalRowHeight = 12.5;
float barrierVerticalColumnWidth = 12.5;
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
TwinstonesStonesView* square = [[TwinstonesStoneView alloc]
initWithEmptyFrame:CGRectFrame(//spacial equations, not important)
column:col
row:row
board:board];
BoardCellState state = [board cellStateAtColumn:col andRow:row];
if (state == BoardCellStateStoneOne) {
// _stoneUnoView is a public property
// 'stoneOneCreation' creates a UIImageView of the stone
_stoneUnoView = [UIImageView stoneOneCreation];
[self addSubview:square];
[square addSubview:_stoneUnoView];
[_array insertObject:_stoneUnoView atIndex:0];
} else if (state == BoardCellStateStoneTwo) {
// same idea as above
_stoneDueView = [UIImageView stoneTwoCreation];
[self addSubview:square];
[square addSubview:_stoneDueView];
[_array insertObject:_stoneDueView atIndex:1];
} else {
// based on the 'init' method I write below, I assumed this
// would return an empty square cell
[self addSubview:square];
[_emptyArray insertObject:square atIndex:_i];
_i++;
}
}
}
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (UIView*)stoneUnoView {
return _stoneUnoView;
}
- (UIView*)stoneDueView {
return _stoneDueView;
}
- (id)initWithEmptyFrame:(CGRect)frame
column:(NSUInteger)column
row:(NSUInteger)row
board:(TwinstonesBoardModel*)board
{
self = [super initWithFrame:frame];
return self;
}
- (void)swipeLeft:(UIGestureRecognizer*)recognizer
{
NSLog(#"Swipe Left");
UIView* view = recognizer.view;
[self move:CGPointMake(-1, 0) withView:view];
}
- (void)move:(CGPoint)direction withView:view {
// whatever code I decide to put for stone movement
}
#end
I apologize for the (probably) unnecessary length, I've just trying to figure this out for a couple days and have had no luck. Here's the bullet points of what I'm trying to do:
1. setInititalStateMain sets the placements of two stones in a 5x5 grid
2. In GameViewController.m, I'm trying to capture the 'stoneUnoView' and
'stoneDueView' properties (set in the TwinstonesStoneView.m file), give them swipe gestures, and interact with them using the methods provided in TwinstonesStoneView.m.
3. Am I generating too many views? The catch is that everything works in terms of what I'm able to see on my IPhone when I run the program. The stones show up on my screen, but when I try to interact with them, not even the 'NSLog' message shows up in the console.
4. The 'stoneOneCreation' method (and ...two) are UIImageView's, but, as you can see, I store them in a UIView pointer.
5. I also used '[one setUserInteractionEnabled:YES]' (and ...two) but that didn't help either.
6. If I add the gesture recognizer to self.view, everything works (the displays of the stones, gameboard, and other graphics appears, and when I interact with ANY part of the screen, I output the directions to the console......just not stone-specific interaction).
Thank you so very much for putting up with all of this, this will really help if someone knows what's wrong. PS: all file #import's are correct, so that isn't a problem.
I am using XCode 7, Objective-C language, and developing for iOS
Anthony
One thing that catches my eye is I don't think you can add the same gesture recognizer to multiple views. I suspect, at best, only the last view is actually receiving it.
try this but i am not sure try this, just create 2 swipe gestures
in GameViewController.m
- (void)viewDidLoad {
[super viewLoad];
//.... other code
//comment below line
// UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
//initWithTarget:self //setting self is the problem is the problem
//action:#selector(swipeLeft:)];
UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:stoneOne //set target will be one
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[one addGestureRecognizer:swipeLeft];
UISwipeGestureRecognizer* swipeLeft_2 = [[UISwipeGestureRecognizer alloc]
initWithTarget:stoneTwo //this will be two
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[two addGestureRecognizer:swipeLeft_2]; //set the gesture
}
u are setting the gesture to self which means the actions are sent to GameViewController.m but we want actions to be in TwinstonesStoneView.m so change the target to view to TwinstonesStoneView. And also if it is image views u are adding gestures, then enable user interaction for each image views setUserInteractionEnabled:
just try it
Here's my GameViewController.m file:
- (void)viewDidLoad {
[super viewLoad];
.
.
.
_board = [[TwinstonesBoardModel alloc] init];
[_board setToInitialStateMain];
TwinstonesStoneView* twinstonesBoard = [[TwinstonesStoneView alloc]
initWithMainFrame:CGRectMake(12, 160, 301.5, 302.5)
andBoard:_board];
[self.view addSubview:twinstonesBoard];
TwinstonesStonesView *stoneOne = [[TwinstonesStoneView alloc] init];
TwinstonesStonesView *one = (TwinstonesStoneView*)stoneOne.stoneUnoView;
TwinstonesStonesView *stoneTwo = [[TwinstonesStoneView alloc] init];
TwinstonesStonesView *two = (TwinstonesStoneView*)stoneTwo.stoneDueView;
UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[one addGestureRecognizer:swipeLeft];
[two addGestureRecognizer:swipeLeft];
Here's the relevant code in my TwinstonesStoneView.m file:
#implementation TwinstonesStoneView
{
NSMutableArray* _array;
NSMutableArray* _emptyArray;
CGRect _frame;
NSUInteger _column;
NSUInteger _row;
TwinstonesBoardModel* _board;
int _i;
}
- (id)initWithMainFrame:(CGRect)frame andBoard:
(TwinstonesBoardModel*)board
{
if (Self = [super initWithFrame:frame])
{
float rowHeight = 49.0;
float columnWidth = 49.0;
float barrierHorizontalRowHeight = 12.5;
float barrierVerticalColumnWidth = 12.5;
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
TwinstonesStonesView* square = [[TwinstonesStoneView alloc]
initWithEmptyFrame:CGRectFrame(//spacial equations, not important)
column:col
row:row
board:board];
BoardCellState state = [board cellStateAtColumn:col andRow:row];
if (state == BoardCellStateStoneOne) {
// _stoneUnoView is a public property
// 'stoneOneCreation' creates a UIImageView of the stone
_stoneUnoView = [UIImageView stoneOneCreation];
[self addSubview:square];
[square addSubview:_stoneUnoView];
[_array insertObject:_stoneUnoView atIndex:0];
} else if (state == BoardCellStateStoneTwo) {
// same idea as above
_stoneDueView = [UIImageView stoneTwoCreation];
[self addSubview:square];
[square addSubview:_stoneDueView];
[_array insertObject:_stoneDueView atIndex:1];
} else {
// based on the 'init' method I write below, I assumed this
// would return an empty square cell
[self addSubview:square];
[_emptyArray insertObject:square atIndex:_i];
_i++;
}
}
}
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (UIView*)stoneUnoView {
return _stoneUnoView;
}
- (UIView*)stoneDueView {
return _stoneDueView;
}
- (id)initWithEmptyFrame:(CGRect)frame
column:(NSUInteger)column
row:(NSUInteger)row
board:(TwinstonesBoardModel*)board
{
self = [super initWithFrame:frame];
return self;
}
- (void)swipeLeft:(UIGestureRecognizer*)recognizer
{
NSLog(#"Swipe Left");
UIView* view = recognizer.view;
[self move:CGPointMake(-1, 0) withView:view];
}
- (void)move:(CGPoint)direction withView:view {
// whatever code I decide to put for stone movement
}
#end
I apologize for the (probably) unnecessary length, I've just trying to figure this out for a couple days and have had no luck. Here's the bullet points of what I'm trying to do:
setInititalStateMain sets the placements of two stones in a 5x5 grid
In GameViewController.m, I'm trying to capture the 'stoneUnoView' and 'stoneDueView' properties (set in the TwinstonesStoneView.m file), give them swipe gestures, and interact with them using the methods provided in TwinstonesStoneView.m.
Am I generating too many views? The catch is that everything works in terms of what I'm able to see on my IPhone when I run the program. The stones show up on my screen, but when I try to interact with them, not even the 'NSLog' message shows up in the console.
The 'stoneOneCreation' method (and ...two) are UIImageView's, but, as you can see, I store them in a UIView pointer.
I also used '[one setUserInteractionEnabled:YES]' (and ...two) but that didn't help either.
If I add the gesture recognizer to self.view, everything works (the displays of the stones, gameboard, and other graphics appears, and when I interact with ANY part of the screen, I output the directions to the console......just not stone-specific interaction).
Thank you so very much for putting up with all of this, this will really help if someone knows what's wrong. PS: all file #import's are correct, so that isn't a problem.
I am using XCode 7, Objective-C language, and developing for iOS
Anthony
You should add different instances of the swipe gesture recogniser to different instances of UIView.
UISwipeGestureRecognizer* swipeLeft1 = [[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(swipeLeft:)];
swipeLeft1.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft1.numberOfTouchesRequired = 1;
[one addGestureRecognizer:swipeLeft1];
UISwipeGestureRecognizer* swipeLeft2 = [[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(swipeLeft:)];
swipeLeft2.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft2.numberOfTouchesRequired = 1;
[two addGestureRecognizer:swipeLeft2];
I assume it is because the gestire recogniser has readonly view property.
Hi may be user interaction is disabled for that views , gestures working only for the views which have the userInteractionEnable = YES.
I am confused with this logic, please help me find a solution.
I am making a uibutton with every touch on UIview and it works in principle. But the button should not overlap with the previous button when touching a second time.
Here is the code for creating a button on a 'touch ended' event.
int const kRadius = 4;
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
loop = [[MagnifierView alloc] init];
loop.viewToMagnify = self;
[loop setNeedsDisplay];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[btnCamera removeFromSuperview];
if(self.activateEditMode){
self.touchTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:#selector(addLoop)
userInfo:nil
repeats:NO];
// just create one loop and re-use it.
if(loop == nil){
loop = [[MagnifierView alloc] init];
loop.viewToMagnify = self;
}
UITouch *touch = [touches anyObject];
loop.touchPoint = [touch locationInView:self];
[loop setNeedsDisplay];
}else{
// Message
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self handleAction:touches];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.touchTimer invalidate];
self.touchTimer = nil;
if(self.activateEditMode){
[self createCameraBtn];
[loop removeFromSuperview];
[self setBackgroundColor:[UIColor colorWithRed:(102/255) green:(102/255) blue:(102/255) alpha:1]];
}
}
Whenever the user is touching the view I am taking the x,y value of the view and save them into a CGPoint loop.touchPoint
and I also save the x,y values into a database to check before creating the next button against the previous x,y values which I stored in the database.
So far everything is ok.
When I am handling the previous values, I am not doing it correctly in the code.
Handling code and button creation
- (BOOL)handleOverlapping{
for (ImageInfo *img in self.profileInfo.imageInfo)
{
int xr = [img.xcord intValue] + kRadius;
int yr = [img.ycord intValue] + kRadius;
if ((([selectedXCord intValue] - kRadius) <= xr) && (([selectedYCord intValue] - kRadius) <=yr))
{
[CSNotificationView showInViewController:[(SkinViewController *)[self.superview nextResponder] navigationController]
style:CSNotificationViewStyleError message:kOVERLAPING_REDDOT_ERROE];
return false;
}
else if ((([selectedXCord intValue] - kRadius+10) <= xr) && (([selectedYCord intValue] - kRadius+10) <=yr))
{
[CSNotificationView showInViewController:[(SkinViewController *)[self.superview nextResponder] navigationController]
style:CSNotificationViewStyleError message:kOVERLAPING_REDDOT_ERROE];
return false;
}
}
return true;
}
button creation
- (void)createCameraBtn{
//[self colorOfPoint:loop.touchPoint];
selectedXCord = [NSNumber numberWithDouble:loop.touchPoint.x-12];
selectedYCord = [NSNumber numberWithDouble:loop.touchPoint.y-75];
// Check whether user focusing on monitored region.
if(![self handleOverlapping])
return;
// else if (![self red:red green:green blue:blue])
// return;
btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
btnCamera.frame = CGRectMake(loop.touchPoint.x-12, loop.touchPoint.y-75, 25, 25);
[btnCamera setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btnCamera setImage:[UIImage imageNamed:#"camera.png"] forState:UIControlStateNormal];
[btnCamera addTarget:self action:#selector(captureSkin) forControlEvents:UIControlEventTouchDown];
[self addSubview:btnCamera];
}
I think I am wrongly handling the overlap method.
In this method
1. xr,yr are the x,y values of the previous button,
2. selectedYcord,selectedXcore is the current touch position.
3. every button has width and height of 25
What I want to do here is to make sure that the second button does not overlap with previous one.
example x,top,y,bottom values.
It can create button minus 10 points with respect to the previous button for any side.
Thanks in advance.
Acutally My code is corret,i did mistake in a for loop..its checking every single time because i returned a value so it never check another button.finally i came to solution by changing code like this..
- (BOOL)handleOverlapping{
BOOL firstCondition=false;
BOOL secondCondition=false;
for (ImageInfo *img in self.profileInfo.imageInfo){
int xr = [img.xcord intValue];
int yr = [img.ycord intValue];
if (xr+12<=[selectedXCord intValue]||xr-12>=[selectedXCord intValue]){
firstCondition=true;
}
else if (yr+12<=[selectedYCord intValue]||yr-12>=[selectedYCord intValue]){
secondCondition=true;
}
else
{
[CSNotificationView showInViewController:[(SkinViewController *)[self.superview nextResponder] navigationController]
style:CSNotificationViewStyleError message:kOVERLAPING_REDDOT_ERROE];
return false;
}
}
if (firstCondition || secondCondition){
return true;
}
return true;
}
when I tested my App in instruments for memory leak I found nothing(running using simulator).But When I run it in a mobile and then checked, there are many leaks in UIKit objects. This happening in every view.In simulator no such leaks are showing.
Below is the screenshot of the instrument where some leakage happened.
When I moved to secondViewController from HomeView, no leaks found.If again coming back to home,these many leaks are found. So, is it mean that, I have to release/nil all the UI objects which I used in that secondView. For your information, below are the UI objects I used in secondView.
1.Two Background UIImageView
2.One TitleBar UIImageView
3.3 UIButtons(Back,left and right button for iCarousel)
4.One iCarousel view
5.UIPageController(For this I have used a third Party code SMPageControl)
6.One title label.
Note : Mine is Non-ARC code.
Did anyone faced this problem before.How can I overcome this problem,since I have this problem in every View in my App.Because of this, my App getting memory waring frequently and crashing often.
Thank you.
Below is the my implementation file of that View.
EDIT1 :
#implementation CatalogueViewController
#synthesize deptCarousel = _deptCarousel;
#synthesize carouselItems = _carouselItems;
#synthesize categorymAr = _categorymAr;
#synthesize spacePageControl = _spacePageControl;
#synthesize wrap;
- (void)dealloc {
_deptCarousel = nil;
[_categorymAr release];
_categorymAr = nil;
_deptCarousel.delegate = nil;
_deptCarousel.dataSource = nil;
[_deptCarousel release];
[_carouselItems release];
[viewGesture release];
viewGesture = nil;
[_spacePageControl release];
_spacePageControl = nil;
imgViewBG = nil;
imgViewBG2 = nil;
btnPrev = nil;
btnNext = nil;
// [self releaseObjects];
[super dealloc];
}
- ( IBAction) btnBackClicked {
[self.navigationController popViewControllerAnimated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = NSLocalizedString(#"catalogue", #"Catalogue");
// Do any additional setup after loading the view from its nib.
_deptCarousel.type = iCarouselTypeLinear;
_deptCarousel.scrollSpeed = 0.3f;
_deptCarousel.bounceDistance = 0.1f;
_deptCarousel.scrollToItemBoundary = YES;
_deptCarousel.stopAtItemBoundary = YES;
[_deptCarousel setScrollEnabled:NO];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeNext:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[viewGesture addGestureRecognizer:swipeLeft];
[swipeLeft release];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipePrev:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[viewGesture addGestureRecognizer:swipeRight];
[swipeRight release];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
[viewGesture addGestureRecognizer:singleTap];
[singleTap release];
_carouselItems = [[NSMutableArray alloc] initWithCapacity:1];
_categorymAr = [[NSMutableArray alloc] initWithCapacity:1];
[self addCatalogues];
_spacePageControl.numberOfPages = [_categorymAr count];
[_spacePageControl setPageIndicatorImage:[UIImage imageNamed:IS_IPAD?#"Marker1.fw.png" : #"Markeri.png"]];
[_spacePageControl setCurrentPageIndicatorImage:[UIImage imageNamed:IS_IPAD?#"Marker-Highlight.png" : #"Marker-Highlight_i.png"]];
[_spacePageControl addTarget:self action:#selector(spacePageControl:) forControlEvents:UIControlEventValueChanged];
}
- (void)spacePageControl:(SMPageControl *)sender{
[_deptCarousel scrollToItemAtIndex:sender.currentPage animated:YES];
}
- ( void ) addCatalogues {
[_categorymAr addObjectsFromArray:[[DBModel database] categoryList]];
for (int i = 0; i < [_categorymAr count]; i++) {
[_carouselItems addObject:[NSNumber numberWithInt:i]];
}
[_deptCarousel reloadData];
}
- (void)viewDidUnload{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[self phoneType];
[super viewWillAppear:animated];
if (IS_IPAD) {
UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
[self handleOrientation:statusBarOrientation];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- ( void ) phoneType{
if(!IS_IPAD){
if(IS_IPHONE5){
imgViewBG.image = [UIImage imageNamed:#"Background5_5.jpg"];
imgViewBG.center = CGPointMake(162,265);
imgViewBG2.image = [UIImage imageNamed:#"Background11_5.png"];
_spacePageControl.center = CGPointMake(160, 478);
_deptCarousel.center = CGPointMake(160, 355);
viewGesture.center = CGPointMake(160, 355);
btnPrev.center = CGPointMake(25, 355);
btnNext.center = CGPointMake(295, 355);
}
else{
imgViewBG.image = [UIImage imageNamed:#"Background5.jpg"];
imgViewBG2.image = [UIImage imageNamed:#"Background9.png"];
}
}
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
textFieldSearch.placeholder = #"";
UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[clearButton setImage:[UIImage imageNamed:IS_IPAD?#"Btn_X_Large.fw.png":#"Btn_X.fw.png"] forState:UIControlStateNormal];
[clearButton addTarget:self action:#selector(btnClearTextField) forControlEvents:UIControlEventTouchUpInside];
[textFieldSearch setRightViewMode:UITextFieldViewModeAlways];
[textFieldSearch setRightView:clearButton];
[clearButton release];
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[textFieldSearch setRightView:nil];
if ([textFieldSearch.text isEqualToString:#""]) {
textFieldSearch.placeholder = NSLocalizedString(#"hud_search_for_a_product_here",#"");
}
}
-(IBAction)btnClearTextField{
textFieldSearch.text = #"";
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (IS_IPAD) {
return YES;
} else {
return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation )toInterfaceOrientation duration:(NSTimeInterval)duration{
if (IS_IPAD) {
[self handleOrientation:toInterfaceOrientation];
}
}
- ( void ) handleOrientation:(UIInterfaceOrientation )toInterfaceOrientation {
if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
imgViewBG.image = [UIImage imageNamed:#"Background_Catalogue_P.jpg"];
imgViewBG2.image = [UIImage imageNamed:#"Background_Overlay_P.fw.png"];
btnPrev.center = CGPointMake(90, 640);
btnNext.center = CGPointMake(677, 640);
textFieldSearch.frame = CGRectMake(187, 54, 418, 25);
_deptCarousel.frame = CGRectMake(235, 250, 300, 800);
_spacePageControl.center = CGPointMake(385, 920);
viewGesture.center = CGPointMake(385, 658);
}else {
imgViewBG.image = [UIImage imageNamed:#"Background_Catalogue_L.jpg"];
imgViewBG2.image = [UIImage imageNamed:#"Background_Overlay_L.fw.png"];
btnPrev.center = CGPointMake(54, 385);
btnNext.center = CGPointMake(640, 385);
textFieldSearch.frame = CGRectMake(240, 55, 567, 25);
_deptCarousel.frame = CGRectMake(50, 250, 600, 300);
_spacePageControl.center = CGPointMake(346, 660);
viewGesture.center = CGPointMake(347, 405);
}
}
- ( IBAction )btnDepartmentClicked:(id)sender {
int btnTag = [sender tag];
ProductCategoriesViewController *productView = [[ProductCategoriesViewController alloc] initWithNibName:#"ProductCategoriesView" bundle:nil];
if ( btnTag == 0 ) {
[productView setStrTitle:NSLocalizedString(#"women", #"Women")];
}else if ( btnTag == 1 ) {
[productView setStrTitle:NSLocalizedString(#"men", #"Men")];
} else {
[productView setStrTitle:NSLocalizedString(#"sports", #"Sports")];
}
[self.navigationController pushViewController:productView animated:YES];
[productView release];
}
- ( BOOL ) textFieldShouldReturn:( UITextField * )textField {
[textField resignFirstResponder];
[Flurry logEvent:#"Product searched" withParameters:[NSDictionary dictionaryWithObjectsAndKeys:textField.text,#"1", nil]];
[self productSearch:textField.text isBar:NO isQR:NO];
return YES;
}
- ( void ) productSearch:( NSString * )_searchText isBar:( BOOL )_isBar isQR:( BOOL )_isQr {
if ([_searchText isEqualToString:#""]) {
return;
}
NSMutableArray *ProductList = [[NSMutableArray alloc] init];
[ProductList addObjectsFromArray:[[DBModel database] productSearch:_searchText isBar:_isBar isQR:_isQr]];
if ( [ProductList count] == 0 ) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"product", #"")
message:NSLocalizedString(#"cannot_find_product", #"")
delegate:nil
cancelButtonTitle:NSLocalizedString(#"ok", #"")
otherButtonTitles:nil];
[alert show];
[alert release];
} else {
GeneralProductListViewController *generalProductList = [[GeneralProductListViewController alloc] initWithNibName:IS_IPAD?#"GeneralProductListView~iPad": #"GeneralProductListView" bundle:nil];
[generalProductList setMArProducts:ProductList];
[self.navigationController pushViewController:generalProductList animated:YES];
[generalProductList release];
}
[ProductList release];
}
-(IBAction) spin:(id)sender {
if([sender tag]==0)
{
[_deptCarousel scrollToItemAtIndex:[self.deptCarousel currentItemIndex]+1 animated:YES];
// [_deptCarousel scrollByNumberOfItems:1 duration:2.0];
}
else{
[_deptCarousel scrollToItemAtIndex:[self.deptCarousel currentItemIndex]-1 animated:YES];
}
}
-(void)swipeNext:(UISwipeGestureRecognizer *)recognizer{
[_deptCarousel scrollToItemAtIndex:[self.deptCarousel currentItemIndex]+1 animated:YES];
}
-(void)swipePrev:(UISwipeGestureRecognizer *)recognizer{
[_deptCarousel scrollToItemAtIndex:[self.deptCarousel currentItemIndex]-1 animated:YES];
}
-(void) handleSingleTap:(UITapGestureRecognizer *)recognizer{
if ([_categorymAr count] > 0) {
ProductCategoriesViewController *prodCatView = [[ProductCategoriesViewController alloc] initWithNibName:IS_IPAD ?
#"ProductCategoriesView~iPad" : #"ProductCategoriesView" bundle:nil];
Category *categoryObj = [_categorymAr objectAtIndex:[self.deptCarousel currentItemIndex]];
[prodCatView setStrTitle:categoryObj.categoryName];
[prodCatView setCategoryId:categoryObj.categoryId];
[Flurry logEvent:#"Category List" withParameters:[NSDictionary dictionaryWithObjectsAndKeys:categoryObj.categoryName,[NSString stringWithFormat:#"%d",categoryObj.categoryId], nil]];
[self.navigationController pushViewController:prodCatView animated:YES];
[prodCatView release];
}
}
//-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// pageControl.currentPage = [self.deptCarousel currentItemIndex] ;
//}
#pragma mark
#pragma mark NavigationBarViewDelegate metho
- ( void ) navigationBackClicked {
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark iCarousel methods
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return [_carouselItems count];
}
- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel
{
//limit the number of items views loaded concurrently (for performance reasons)
return NUMBER_OF_VISIBLE_ITEMS;
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index
{
Category *categoryObj = [_categorymAr objectAtIndex:index];
//create a numbered view
UIView *view = nil;
NSString *imagePath = [[APP_CACHES_DIR stringByAppendingPathComponent:#"catalogues"] stringByAppendingString:[NSString stringWithFormat:#"/%d.jpg", categoryObj.categoryId]];
if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:IS_IPAD?#"Gallery Placeholder.png":#"Gallery Placeholder.png"]] autorelease];
} else {
view = [[[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[APP_CACHES_DIR stringByAppendingPathComponent:#"catalogues"] stringByAppendingString:[NSString stringWithFormat:#"/%d.jpg", categoryObj.categoryId]]]] autorelease];
}
if (IS_IPAD) {
view.frame = CGRectMake(0, 0, 420, 420);
} else {
view.frame = CGRectMake(0, 0, 200, 200);
}
// UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(view.bounds.origin.x, view.bounds.origin.y+view.bounds.size.height, view.bounds.size.width, 44)] autorelease];
// label.text = categoryObj.categoryName;
// label.textColor = [UIColor blackColor];
// label.backgroundColor = [UIColor clearColor];
// label.textAlignment = UITextAlignmentCenter;
// label.font = [UIFont fontWithName:#"Helvetica-Bold" size:IS_IPAD?26:14];
// [view addSubview:label];
return view;
}
- (NSUInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return INCLUDE_PLACEHOLDERS? 2: 0;
}
- (UIView *)carousel:(iCarousel *)carousel placeholderViewAtIndex:(NSUInteger)index
{
//create a placeholder view
UIView *view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:view.bounds] autorelease];
label.text = (index == 0)? #"[": #"]";
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
label.font = [label.font fontWithSize:50];
_spacePageControl.currentPage = index;
// [view addSubview:label];
return view;
}
- (CGFloat)carouselItemWidth:(iCarousel *)carousel
{
//usually this should be slightly wider than the item views
return ITEM_SPACING;
}
- (CATransform3D)carousel:(iCarousel *)_carousel transformForItemView:(UIView *)view withOffset:(CGFloat)offset
{
//implement 'flip3D' style carousel
//set opacity based on distance from camera
view.alpha = 1.0 - fminf(fmaxf(offset, 0.0), 1.0);
//do 3d transform
CATransform3D transform = CATransform3DIdentity;
transform.m34 = _deptCarousel.perspective;
transform = CATransform3DRotate(transform, M_PI / 8.0, 0, 1.0, 0);
return CATransform3DTranslate(transform, 0.0, 0.0, offset * _deptCarousel.itemWidth);
}
- (BOOL)carouselShouldWrap:(iCarousel *)carousel
{
//wrap all carousels
// return NO;
return wrap;
}
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
if (index == [self.deptCarousel currentItemIndex]) {
ProductCategoriesViewController *prodCatView = [[ProductCategoriesViewController alloc] initWithNibName:IS_IPAD ?
#"ProductCategoriesView~iPad" : #"ProductCategoriesView" bundle:nil];
Category *categoryObj = [_categorymAr objectAtIndex:index];
[prodCatView setStrTitle:categoryObj.categoryName];
[prodCatView setCategoryId:categoryObj.categoryId];
[Flurry logEvent:#"Category List" withParameters:[NSDictionary dictionaryWithObjectsAndKeys:categoryObj.categoryName,[NSString stringWithFormat:#"%d",categoryObj.categoryId], nil]];
[self.navigationController pushViewController:prodCatView animated:YES];
[prodCatView release];
}
}
-(void) carouselDidScroll:(iCarousel *)carousel{
// [_deptCarousel scrollToItemAtIndex:[self.deptCarousel currentItemIndex]+3 animated:YES];
// [_deptCarousel scrollByNumberOfItems:1 duration:1];
}
- (void)carouselCurrentItemIndexUpdated:(iCarousel *)carousel{
_spacePageControl.currentPage = [self.deptCarousel currentItemIndex];
}
- ( IBAction ) myCart {
if ( [[DBModel database] isShoppingListEmpty] ) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"at_shopping_cart", #"")
message:NSLocalizedString(#"amsg_shopping_cart_empty", #"")
delegate:nil cancelButtonTitle:NSLocalizedString(#"ok", #"") otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
MyCartViewController *myCartView = [[MyCartViewController alloc] initWithNibName:IS_IPAD ? #"MyCartView~iPad" : #"MyCartView" bundle:nil];
[self.navigationController pushViewController:myCartView animated:YES];
[myCartView release];
}
First, as noted before, use ARC. There is no single thing you could do that will more improve memory management.
Whether you use ARC or not, you should always use accessors to access your ivars (except in init and dealloc). As noted by #LombaX, you're setting your ivars incorrectly in viewDidLoad. Using accessors would help this.
You should run the static analyzer, which will help you find other memory mistakes.
I would suspect that you have an IBOutlet that is configured as retain and that you are not releasing in dealloc. That is the most likely cause of the leaks I'm seeing in your screenshots. ARC will generally make such problems go away automatically.
It is very possible that you have a retain loop. This generally would not show up as a leak. You should use heapshot to investigate that. Your leaks are pretty small; they may not be the actual cause of memory warnings. What you want to investigate (with the Allocations instrument) is what is actually significantly growing your memory use.
But first ARC. Then accessors. Then remove all build warnings. Then remove all Static Analyzer warnings. Then use the Allocations instrument.
Side note: the fact that it says the responsible party is "UIKit" does not mean that this is a bug in UIKit. It just means that UIKit allocated the memory that was later leaked. The cause of the leak could be elsewhere. (That said, UIKit does have several small leaks in it. In general they should not give you trouble, but you may never be able to get rid of 100% of small leaks in an iOS app.)
First:
you have a possible and visible leak, but I'm not sure if it is the same leak you have found in instruments:
These two lines are in your viewDidLoad method
_carouselItems = [[NSMutableArray alloc] initWithCapacity:1];
_categorymAr = [[NSMutableArray alloc] initWithCapacity:1];
But: viewDidLoad: is called every time the view is loaded by it's controller. If the controller purges the view (for example after a memory warning), at the second viewDidLoad your _carouselItems and _categorymAr instance variables will lost the reference to the previously created NSMutableArray, causing a leak
So, change that lines and use the syntesized setters:
self.carouselItems = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
self.categorymAr = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
the syntesized setter is configured to release the previous object before assignin a new one.
However: it's possible that you have another leak.
If you can reproduce the leak simply (if I understand, the leak appears simply moving from a VC to another), you can use the "heapshot" function of instruments.
Assuming that your leak appears moving from the first VC to the second and coming back:
open instruments with the allocations tool
go from the first VC to the second and come back.
press "mark heap" on the left. A line will appear.
go again from the first VC to the second and come back.
press "heapshot" again
do this several times (9-10)
the heapshot tool takes a "snapshot" of the living objects at the time you pushed the button and shows you only the difference.
If there are 2-3 new objects, you will see it in the list.
This is a good starting point to investigate a leak.
Look at the attached image:
Consider that you must mark the heap several time and discriminate "false positive" by looking at the object created, in my example you can se a possible leak (heapshot5, 1,66KB), but after looking at the content it's not --> it was a background task that started in that moment.
Moreover, delays of the autorelease pool and the cache of some UIKit objects can show something in the heapshot, this is why I say to try it several times.
One easy way to detect where your leaks come from is to use the Extended Detail view of the Instruments.
To do that click on "View"->"Extended detail" and a right menu with the stack trace of the "leak" will appear. There you will easily find the leaking code for each leak and if they come from your app.
I just spent most of a day tracking down a very strange case where calling resignFirstResponder on the active UITextField did not hide the keyboard, even though the textfield was the first responder. This happens when I push a view controller on top of another view controller with an active text field. The keyboard goes away (as expected). But if I bring the keyboard back by touching a textfield in the 2nd view controller, subsequent calls to resignFirstResponder have no effect.
Here's simple code to reproduce the issue. This code is a view controller with a nav bar button to hide the keyboard, and another to push another copy of itself (with a confirmation UIAlertView). The first copy works without problem. However, if you push a 2nd copy (when the first copy has a visible keyboard) it is impossible to dismiss the keyboard. This only happens if there is a UIAlertView (the confirmation) on the screen when the 2nd copy is pushed. If you remove the #define ALERT line, everything works.
Does anyone know what is happening here? It looks like the UIALertView window is somehow interfering with the keyboard and keeping it's window from disappearing, which then confuses the next view. Is there any solution here other than pushing the 2nd view controller on a timer after the UIALertView is gone?
Sorry for the complex description. This is runnable code. I hope that the code is clear.
#implementation DemoViewController
- (id) init {
if (!(self = [super init]))
return nil;
return self;
}
- (void) dealloc {
[_inputTextfield release];
[super dealloc];
}
- (void) loadView {
UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
_inputTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0., 0., 320., 44.)];
_inputTextfield.borderStyle = UITextBorderStyleRoundedRect;
_inputTextfield.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
_inputTextfield.keyboardAppearance = UIKeyboardAppearanceAlert;
_inputTextfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
_inputTextfield.autocorrectionType = UITextAutocorrectionTypeNo;
_inputTextfield.keyboardType = UIKeyboardTypeDefault;
[view addSubview:_inputTextfield];
self.view = view;
[view release];
}
- (void) viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
UIButton *downButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downButton setTitle: #"keyboard down" forState:UIControlStateNormal];
[downButton addTarget:self action:#selector(downButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[downButton sizeToFit];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:downButton] autorelease];
UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
[nextButton setTitle: #"next" forState:UIControlStateNormal];
[nextButton addTarget:self action:#selector(nextButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[nextButton sizeToFit];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:nextButton] autorelease];;
}
- (void) viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
[_inputTextfield resignFirstResponder];
}
- (void) downButtonPressed:(id)sender {
[_inputTextfield resignFirstResponder];
}
#define ALERT
- (void) alertView:(UIAlertView *) alertView didDismissWithButtonIndex:(NSInteger) buttonIndex {
if (alertView.cancelButtonIndex == buttonIndex) {
return;
}
[self _nextButtonPressed];
}
- (void) _nextButtonPressed {
DemoViewController *nextViewController = [[DemoViewController alloc] init];
[self.navigationController pushViewController:nextViewController];
[nextViewController release];
}
- (void) nextButtonPressed:(id)sender {
#ifdef ALERT
UIAlertView *alert = [[UIAlertView alloc] init];
alert.message = #"Next view?";
alert.cancelButtonIndex = [alert addButtonWithTitle:#"No"];
[alert addButtonWithTitle:#"Yes"];
alert.delegate = self;
[alert show];
[alert release];
#else
[self _nextButtonPressed];
#endif
}
If you had bad luck resigning your first responders, here are a few solutions that might help:
Determine who has remained the first responder after your last call to resign first responder.
Try resigning all first responders by a single call to self.view (container view)
[self.view endEditing:YES];
ONLY if you've tried all the above methods and none worked, consider using this workaround.
-(BOOL)textViewShouldEndEditing:(UITextView *)textView {
NSArray *wins = [[UIApplication sharedApplication] windows];
if ([wins count] > 1) {
UIWindow *keyboardWindow = [wins objectAtIndex:1];
keyboardWindow.hidden = YES;
}
return YES;
}