uipagecontrol indicator(dot)issue - iphone

Hai All...
I want to change the uipagecontroller indicator(dot) color...For that i'm doing the below steps.
Create new class named as PageControl with 2 methods
1.- (void) setCurrentPage:(NSInteger)page
2.- (void) setNumberOfPages:(NSInteger)pages
- (void) setCurrentPage:(NSInteger)page
{
NSLog(#"setCurrentPage");
[super setCurrentPage:page];
NSString* imgActive = [[NSBundle mainBundle] pathForResource:#"activeimage" ofType:#"png"];
NSString* imgInactive = [[NSBundle mainBundle] pathForResource:#"inactive" ofType:#"png"];
for (NSUInteger subviewIndex = 0; subviewIndex < [self.subviews count]; subviewIndex++)
{
UIImageView* subview= [self.subviews objectAtIndex:subviewIndex];
if (subviewIndex == page)
[subview setImage:[UIImage imageWithContentsOfFile:imgActive]];
else
[subview setImage:[UIImage imageWithContentsOfFile:imgInactive]];
subview.frame = CGRectMake(subview.frame.origin.x, subview.frame.origin.y, 10,10);
}
}
- (void) setNumberOfPages:(NSInteger)pages
{
NSLog(#"setNumberOfPages");
[super setNumberOfPages:pages];
NSString* img = [[NSBundle mainBundle] pathForResource:#"inactive" ofType:#"png"];
for (NSUInteger subviewIndex = 0; subviewIndex < [self.subviews count]; subviewIndex++)
{
UIImageView* subview= [self.subviews objectAtIndex:subviewIndex];
[subview setImage:[UIImage imageWithContentsOfFile:img]];
subview.frame = CGRectMake(subview.frame.origin.x, subview.frame.origin.y, 10,10);
}
}
Already i'm having one view with pagecontrol and scrollview...Here what i'm doing is select the uipagecontroller from nib and choose identity inspector and select the class name PageControl(newly created class with 2 methods)it works for changing the color while swipe the images but,it didn't works for clicking the pagecontrol for moving to next page...
I don't know what shoud i want to include or what mistake i'm doing...please help me out to do this...
Thank You...

If you want to enable page scrolling on click of dot then you need to first of all associate the "value changed" property in your xib file to the action you set in your code.
I have implemented the same functionality in one of my projects so it will definitely work.
- (IBAction)changePage:(id)sender {
int page = pageControl.currentPage;
CGFloat pageWidth = scrollView.frame.size.width;
pageWidth = scrollView.frame.size.width;
pageControl.currentPage = page;
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
}
Cheers

Your above code is crashing in iOS 7.I have found a solution for this problem. I know it is not the way but Sure that it works till iOS 8 will be launched in the market.
Reason for Crash:
in iOS 7 [self.subViews objectAtIndex: i] returns UIView Instead of UIImageView and setImage is not the property of UIView and the app crashes. I solve my problem using this following code.
Check Whether the subview is UIView(for iOS7) or UIImageView(for iOS6 or earlier). And If it is UIView I am going to add UIImageView as subview on that view and voila its working and not crash..!!
-(void) updateDots
{
for (int i = 0; i < [self.subviews count]; i++)
{
UIImageView * dot = [self imageViewForSubview: [self.subviews objectAtIndex: i]];
if (i == self.currentPage) dot.image = activeImage;
else dot.image = inactiveImage;
}
}
- (UIImageView *) imageViewForSubview: (UIView *) view
{
UIImageView * dot = nil;
if ([view isKindOfClass: [UIView class]])
{
for (UIView* subview in view.subviews)
{
if ([subview isKindOfClass:[UIImageView class]])
{
dot = (UIImageView *)subview;
break;
}
}
if (dot == nil)
{
dot = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, view.frame.size.width, view.frame.size.height)];
[view addSubview:dot];
}
}
else
{
dot = (UIImageView *) view;
}
return dot;
}
Hope this solve ur issue too for iOS7. and If Anypone find the optimal solution for that please comment. :)
Happy coding

Related

UIScrollView with rearrangable buttons

I need to implement a pop up menu with a number of buttons on it. I have created the pop up and dynamically added the buttons to it. Now I need to rearrange the buttons like the iPhone home screen does.
When long press gesture occurs the buttons needs to start animating with close button(like that which appears when we try to delete an app from the phone). Further I need to rearrange the position of the button by dragging it. I have added animation to the button's appearance and also close button but I'm struggling to find a way to rearrange the button position. I have searched a lot and found many links regarding this functionality but then most of them are pretty lengthy and complex. I just want a quick/simple one which can be implemented fast.
Any idea guys??
I have same issue and i solved my problem with following code.
1) get your all Images from your Document folder
2) set it in scrollview
3) put UILongPressGestureRecognizer on Imageview. and display cross button.
4) if it delete then repeat step 2 to 4.
No need to arrange the whole item but just remove all item from scrollview and refill it again.
//Document Directory
#define kAppDirectoryPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
#pragma mark - File Functions - Document/Cache Directory Functions
- (void)createDocumentDirectory:(NSString*)pStrDirectoryName
{
NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL];
}
- (NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName
{
NSString *strPath = #"";
if(pStrPathName)
strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName];
return strPath;
}
-(void)setScrollviewItem {
NSArray* subviews = [[NSArray alloc] initWithArray: scrollObj.subviews];
for (UIView* view in subviews) {
if ([view isKindOfClass:[UIImageView class]]) {
[view removeFromSuperview];
}
if ([view isKindOfClass:[UIButton class]]) {
[view removeFromSuperview];
}
}
[subviews release];
[arrSaveImage removeAllObjects];
NSError *error = nil;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[slef getDocumentDirectoryPath:#"MyPhotos"] error:&error];// MyPhoto is my Directory Name.
if (!error) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self ENDSWITH '.png'"];
NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
for (int i=0;i<[imagesOnly count]; i++) {
[arrSaveImage addObject:[imagesOnly objectAtIndex:i]];
}
}
int px=0;
for (int i = 0; i < [arrSaveImage count]; i++) {
UIImageView *imgBackScroll=[[UIImageView alloc] init];
NSString *strPath=[self getDocumentDirectoryPath:#"MyPhotos"];
strPath=[NSString stringWithFormat:#"%#/%#",strPath,[arrSaveImage objectAtIndex:i]];
imgBackScroll.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:strPath]];
imgBackScroll.frame=CGRectMake(px+5, 10, 90, 80);
imgBackScroll.layer.cornerRadius = 5.0;
imgBackScroll.layer.masksToBounds = YES;
imgBackScroll.tag=i;
imgBackScroll.userInteractionEnabled = YES;
[scrollObj addSubview:imgBackScroll];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];//This is your Cross delete button on corner
//[btn setTitle:#"-" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:#"CrossDelete.png"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(deleteButton:) forControlEvents:UIControlEventTouchUpInside];
btn.frame=CGRectMake(imgBackScroll.frame.origin.x-2, 0, 15, 15);
btn.hidden=YES;
btn.tag=i;
[scrollObj addSubview:btn];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(startWobbling:)];
longPressGesture.view.tag=i;
[imgBackScroll addGestureRecognizer:longPressGesture];
[imgBackScroll release];
[longPressGesture release];
px=px+95;
}
scrollObj.contentSize = CGSizeMake(px, scrollObj.frame.size.height);
}
-(void) startWobbling:(UILongPressGestureRecognizer*)gesture{
CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5.0));
CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5.0));
gesture.view.transform = leftWobble; // starting point
[UIView beginAnimations:#"wobble" context:gesture.view];
[UIView setAnimationRepeatAutoreverses:YES]; // important
[UIView setAnimationRepeatCount:11];
[UIView setAnimationDuration:0.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(wobbleEnded:finished:context:)];
gesture.view.transform = rightWobble; // end here & auto-reverse
[UIView commitAnimations];
NSArray* subviews = [[NSArray alloc] initWithArray: scrollObj.subviews];
for (UIView* view in subviews) {
if ([view isKindOfClass:[UIButton class]]) {
if (view.tag==gesture.view.tag) {
view.hidden=NO;
}
}
}
[subviews release];
}
//When Delete button pressed
-(IBAction)deleteButton:(id)sender {
UIButton *bt=(UIButton *)sender;
self.strDeleteFilePath=[FunctionManager getDocumentDirectoryPath:#"MyPhotos"];
self.strDeleteFilePath=[NSString stringWithFormat:#"%#/%#",strDeleteFilePath,[arrSaveImage objectAtIndex:bt.tag]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Are you sure you want to delete this photo" delegate:self cancelButtonTitle:#"Delete" otherButtonTitles:#"Cancel", nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0){
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if(![fileManager removeItemAtPath:self.strDeleteFilePath error:&error]) {
NSLog(#"Delete failed:%#", error);
} else {
NSLog(#"image removed: %#",strDeleteFilePath);
}
[self setScrollviewItem];
}
}
I have tried many libraries and discovered a great and practical solution: UzysGridView.
This is very simple and easy to customize.
Check out these sample code,
https://github.com/gmoledina/GMGridView
http://mobile.tutsplus.com/tutorials/iphone/uicollectionview-layouts/
hope that these sample code fulfil your need..
UICollectionView does it more efficiently.
IF you don't want to user UICollectionView, try to subclass UIScrollView and override layoutSubview method - whenever you need to rearrange the buttons, call setNeedsLayout.
example (Haven't test it):
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat x = 0;
CGFloat y = 0;
CGFloat buttonWidth = 100;
CGFloat buttonHeight = 100;
CGFloat spaceBetweenButtons = 10;
for (UIButton *button in self.subviews)
{
if ([button isKindOfClass:[UIButton class]])
{
button.frame = CGRectMake(x, y, buttonWidth, buttonHeight);
x+=buttonWidth+spaceBetweenButtons;
if (x + buttonWidth > self.frame.size.width)
{
x = 0;
y += spaceBetweenButtons+ buttonHeight;
}
}
}
self.contentSize = CGPointMake(0, y);
}
- (void)rearrange
{
[UIView animateWithDuration:0.2 animations:^{
[self setNeedsLayout];
}];
}

how to hide SPUserResizableView with tag in iphone?

Hi I have a method in which I have created 3 views on a click;
-(void)method{
for (i=0; i<3; i++) {
NSLog(#"i is: %d",i);
NSLog(#"i is: %d",i);
userResizableView = [[SPUserResizableView alloc] initWithFrame:CGRectMake (100,41,60,60)];
userResizableView.tag = i;
imageVw1 = [[UIImageView alloc]initWithFrame:userResizableView.bounds];
imageVw1.image = [UIImage imageNamed:#"redacted2.jpg"];
imageVw1.userInteractionEnabled=YES;
imageVw1.autoresizesSubviews = YES;
imageVw1.alpha = 0.93; // for opacity
userResizableView.contentView = imageVw1;
userResizableView.delegate = self;
[userResizableView showEditingHandles];
currentlyEditingView = userResizableView;
lastEditedView = userResizableView;
[self.view addSubview: userResizableView];
[userResizableView release];
}
}
Now in another method I want to hide these views what I created last.
but I am not able to do it. I am hiding my view is like-
-(void)Hide_method{
// int type instance variable, and a=0; in viewdidload;
userResizableView.tag = a;
userResizableView.hidden = YES;
a++;
}
But only one view is hide and the rest are remaining, no matters how amny times I clicked Hide_method, only one view is hide.
My question is that how to hide last view what I created last. Means views hide like 3,2,1,0. On every time when I clicked hide_method.
Any Idea or suggestions would be highly welcome.
Provide unique tag to not clash with any other subview of self.view with same tag like say any number 999 +.
Make changes accordingly:
for (i=0; i<3; i++) {
SPUserResizableView *userResizableView = [[SPUserResizableView alloc] initWithFrame:CGRectMake(100,41,60,60)];
userResizableView.tag = 999+i;
..........
..........
}
Now hide method would be:
-(void)Hide_method{
// find SPUserResizableView with unique tag
for (i=0; i<3; i++) {
if(i == 2){
SPUserResizableView*userResizableView = (SPUserResizableView *)[self.view viewWithTag:999+i];
userResizableView.hidden = YES;
}
}
EDIT : To restore frame to original store while allocating view
CGRect prevFrame = userResizableView.frame //take frame while allocating userResizableView
Now restore whenever you wanted to original frame like this:
SPUserResizableView*userResizableView = (SPUserResizableView *)[self.view viewWithTag:999+2]; //get last userResizableView
userResizableView.frame = prevFrame;
-(void)Hide_method{
// int type instance variable, and a=0; in viewdidload;
//userResizableView.tag = a;
SPUserResizableView *_view = (SPUserResizableView *)[self.view viewWithTag:a];
userResizableView.hidden = YES;
a++;
}
Try this:
-(void)Hide_method{
//UIView *v = [self.view viewWithTag:a];
SPUserResizableView *v = (SPUserResizableView *)[self.view viewWithTag:a];
if(v)
[v removeFromSuperview];
a++;
}
Method to remove view having tag=a
for (UIView *subview in [self.view subviews])
{
if (subview.tag == a)
{
[subview removeFromSuperview];
}
}

If UITableview is empty show image

I am looking for 3 hours now on Google how to remove the tableview and show an image when the tableview is empty (have no more rows). Does someone know this? I know it's possible, because I saw it on many apps.
What I could find was:
// Check if table view has any cells
int sections = [self.tableView numberOfSections];
BOOL hasRows = NO;
for (int i = 0; i < sections; i++)
hasRows = ([self.tableView numberOfRowsInSection:i] > 0) ? YES : NO;
if (sections == 0 || hasRows == NO)
{
UIImage *image = [UIImage imageNamed:#"test.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Add image view on top of table view
[self.tableView addSubview:imageView];
// Set the background view of the table view
self.tableView.backgroundView = imageView;
}
where to put this?
Thanks!
If your using Storyboard just put your view behind your UITableView
If your array of data is empty when creating it, simply hide your UITableView to show the "empty table" view behind it.
[tableView setHidden:YES];
Please refer to:
http://www.unknownerror.org/Problem/index/905493327/how-do-i-display-a-placeholder-image-when-my-uitableview-has-no-data-yet/
Thanks to Cocoanut and Thomas:
#interface MyTableViewController : UITableViewController
{
BOOL hasAppeared;
BOOL scrollWasEnabled;
UIView *emptyOverlay;
}
- (void) reloadData;
- (void) checkEmpty;
#end
#implementation MyTableViewController
- (void)viewWillAppear:(BOOL)animated
{
[self reloadData];
[super viewWillAppear: animated];
}
- (void)viewDidAppear:(BOOL)animated
{
hasAppeared = YES;
[super viewDidAppear: animated];
[self checkEmpty];
}
- (void)viewDidUnload
{
if (emptyOverlay)
{
self.tableView.scrollEnabled = scrollWasEnabled;
[emptyOverlay removeFromSuperview];
emptyOverlay = nil;
}
}
- (UIView *)makeEmptyOverlayView
{
UIView *emptyView = [[[NSBundle mainBundle] loadNibNamed:#"myEmptyView" owner:self options:nil] objectAtIndex:0];
return emptyView;
}
- (void) reloadData
{
[self.tableView reloadData];
if (hasAppeared &&
[self respondsToSelector: #selector(makeEmptyOverlayView)])
[self checkEmpty];
}
- (void) checkEmpty
{
BOOL isEmpty = YES;
id<UITableViewDataSource> src = self.tableView.dataSource;
NSInteger sections(1);
if ([src respondsToSelector: #selector(numberOfSectionsInTableView:)])
sections = [src numberOfSectionsInTableView: self.tableView];
for (int i = 0; i < sections; ++i)
{
NSInteger rows = [src tableView: self.tableView numberOfRowsInSection: i];
if (rows)
isEmpty = NO;
}
if (!isEmpty != !emptyOverlay)
{
if (isEmpty)
{
scrollWasEnabled = self.tableView.scrollEnabled;
self.tableView.scrollEnabled = NO;
emptyOverlay = [self makeEmptyOverlayView];
[self.tableView addSubview: emptyOverlay];
}
else
{
self.tableView.scrollEnabled = scrollWasEnabled;
[emptyOverlay removeFromSuperview];
emptyOverlay = nil;
}
}
else if (isEmpty)
{
// Make sure it is still above all siblings.
[emptyOverlay removeFromSuperview];
[self.tableView addSubview: emptyOverlay];
}
}
#end
UITableView is a (non direct) subclass of UIView, so what you want to do is easy.
Say that you have this table view as subview of your view controller's view. This case you just create another view with the same frame as the table view, then you remove your table view from the superview, and add the newly created view as subview of your view controller's view. So simply:
UIImageView* view= [[UIImageView alloc] initWithImage: yourImage];
view.frame= tableView.frame;
[tableView removeFromSuperview];
[self.view addSubview: view];
Put it on - (void)viewDidAppear. Good luck ;)

iOS : Cancel a Void function

I have created a method for example changeColor for calling the method we use
[self changeColor];
but how can I cancel these method ?
Edited :
here is my code I have several buttons which they add some image to the image view
- (void) setImagesFrame1 {
NSMutableArray *imageArray = [[NSMutableArray alloc]initWithCapacity:12];
for (int i = 0; i <= 12; i++) {
NSString *fileName = [NSString stringWithFormat:#"a%d.png",i];
UIImage *j = [UIImage imageNamed:fileName];
UIImageView *tempImage = [[UIImageView alloc]initWithImage:j];
[imageArray addObject:tempImage];
[self createPageWithImage:tempImage forPage:i];
}
}
- (void) setImagesFrame2 {
NSMutableArray *imageArray = [[NSMutableArray alloc]initWithCapacity:12];
for (int i = 0; i <= 12; i++) {
NSString *fileName = [NSString stringWithFormat:#"s%d.png",i];
UIImage *j = [UIImage imageNamed:fileName];
UIImageView *tempImage = [[UIImageView alloc]initWithImage:j];
[imageArray addObject:tempImage];
[self createPageWithImage:tempImage forPage:i];
}
}
and so on ...
I call my methods with this action :
- (IBAction)openFrames:(UIButton *)sender {
[captureView addSubview:framesPreviewView];
[framesPreviewView sendSubviewToBack:captureView];
framesPreviewView.frame = CGRectMake(img.bounds.origin.x, img.bounds.origin.y, img.bounds.size.width, img.bounds.size.height);
//buttons
if (sender == frame1) { [self setImagesFrame1]; }
if (sender == frame2) { NSLog(#"frame2"); }
if (sender == frame3) { [self setImagesFrame3]; NSLog(#"frame3"); }
}
when I press frame1 button the images will be added to my view , the problem is when I press frame2 button the images of this method also add to my view I need avoid this situation , it means when I touch every button the methods of other button should be canceled
To leave a void function execute the return statement...
return;
The last view on your subview array will be the image, You should use the method [view removeFrom superView];
However, to do that you need to use fast enumeration(for-In loop) over the subviews array.
If you want to be completely sure , you can check the retuned object, if it belongs to UIImageView Class. Then you should execute remaining statements in you setImages method.
Example: `
UIView *tempView;
for(tempView in self.subviews) {
if([tempView isKindOfClass:[UIImageView class] ]){
[tempView removeFromSuperView];
}
}
`
You can:
disable frame2 button when frame1 is pressed
enable frame2 button when setImagesFrame1 ended
Something like this:
- (void) setImagesFrame1 {
frame2.enabled = NO;
[... your code ...]
frame2.enable;
}
So if someone press button 1, he can't press button 2 (and redraw something) until all operations are completed.

iPhone Page Control only shows on the first page of a UIScrollView

My page control only shows on the first page of the UIScrollView. Once I scroll to the next page it disappears.
Could you tell me what I'm doing wrong? Because I'm curious as to whether I need to add a subview of the page control each time I add a subview to my UIScrollView.
My relevant pieces of code:
-(IBAction)clickPageControl:(id)sender
{
int page=pageControl.currentPage;
CGRect frame=scroller.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scroller scrollRectToVisible:frame animated:YES];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page = scrollView.contentOffset.x/scrollView.frame.size.width;
pageControl.currentPage=page;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
arrayCount = [array count];
scroller.delegate=self;
scroller.pagingEnabled=YES;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
//should have an array of photo objects and the number of objects, correct?
scrollWidth = 0;
scroller.contentSize=CGSizeMake(arrayCount*scroller.frame.size.width, scroller.frame.size.height);
for (int i = 0; i < arrayCount;i++) {
PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:#"PhotoViewController" bundle:nil];
UIImageView *scrollImageView = [[UIImageView alloc] initWithFrame:CGRectOffset(scroller.bounds, scrollWidth, 0)];
CGRect rect = scrollImageView.frame;
pvc.view.frame = rect;
[pvc view];
pvc.label.textColor = [UIColor whiteColor];
id individualPhoto = [array objectAtIndex:i];
NSLog(#"%#",individualPhoto);
NSArray *keys=[individualPhoto allKeys];
NSLog(#"%#",keys);
NSString *imageURL=[individualPhoto objectForKey:#"source"];
//here you can use this imageURL to get image-data and display it in imageView
NSURL *url = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
pvc.imageView.image = [[UIImage alloc] initWithData:data];
pvc.label.text = [NSString stringWithFormat:#"Photo Number: %i", arrayCount];
//check to make sure the proper URL was passed
//I have an imageView next to the UIScrollView to test whether that works - it does.
[scroller addSubview:pvc.view];
[scrollImageView release];
[pvc release];
scrollWidth += scroller.frame.size.width;
}
if (arrayCount > 3) {
pageControl.numberOfPages=3;
} else {
pageControl.numberOfPages=arrayCount;
}
pageControl.currentPage=0;
[self.view addSubview:scroller];
}
You should not add your page control as a subview of the scroll view, this causes it to scroll with the content. Make it a sibling of the scroll view instead.