I have a UITableView containing a list of maps. When an item is selected a new sub view is added to the main window and the map is shown. In my view controller for the map view the following method gets called each time it's displayed:
- (void)showMap {
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:mapImage]];
float imageHeight = tempImageView.image.size.height;
float targetHeight = scrollView.frame.size.height - mapNavigationController.navigationBar.frame.size.height;
scrollView.contentSize = tempImageView.image.size;
scrollView.maximumZoomScale = 1.0;
scrollView.minimumZoomScale = targetHeight / imageHeight;
scrollView.clipsToBounds = YES;
self.imageView = tempImageView;
[tempImageView release];
[scrollView addSubview:imageView];
scrollView.zoomScale = scrollView.minimumZoomScale;}
A new UIImageView is added each time to the UIScrollView and when the view disappears the UIImageView is removed. The zoomScale is calculated so that the image fits according to the aspect ratio.
Now to my problem the first time an item is clicked everything works fine and the map image fills the full height of the UIScrollView, but the next time an item is clicked the height of the UIScrollView is smaller. I also should note that the main window contains a tab bar.
So now to my questions:
How can the UIScrollView change it's size?
And is there any other dynamic way to retrieve the targetHeight?
Thanks in advance!
I was having a similar problem. It turns out the issue was that I was subclassing UIScrollView for the main view of my UIViewController, and the UIViewController had its own ideas about the correct size of the scroll view.
I fixed it by making the main view subclass UIView rather than UIScrollView, then adding a UIScrollView* content_view to the view, and adding my subviews to content_view rather than to self.
Not sure if this helps you or not, however...
Ok, i managed to found a solution my self, maybe not the best but it's dynamic and it works.
But i still don't understand why the height of UIScrollView would change. If someone know why please comment.
NSInteger scrollViewHeight = 0;
- (void)showMap {
if (scrollViewHeight == 0) {
scrollViewHeight = scrollView.frame.size.height;
} else {
scrollView.frame.size.height = scrollViewHeight;
}
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:mapImage]];
float imageWidth = tempImageView.image.size.width;
float imageHeight = tempImageView.image.size.height;
float targetWidth = scrollView.frame.size.width;
float targetHeight = scrollViewHeight - mapNavigationController.navigationBar.frame.size.height;
float scale = targetHeight / imageHeight;
if (scale * imageWidth < targetWidth) {
scale = targetWidth / imageWidth;
}
scrollView.contentSize = tempImageView.image.size;
scrollView.maximumZoomScale = 1.0;
scrollView.minimumZoomScale = scale;
scrollView.clipsToBounds = YES;
self.imageView = tempImageView;
[tempImageView release];
[scrollView addSubview:imageView];
scrollView.zoomScale = scale;}
}
Related
I have UIScrollview that contains different UITableviews. You can scroll through these UITableviews using a UIPagecontrol.
This is how I add my UITableview to the UIScrollview
- (void)loadPage:(NSInteger)page {
if (page < 0 || page >= self.pageStages.count) {
// If it's outside the range of what we have to display, then do nothing
return;
}
// Load an individual page, first seeing if we've already loaded it
UIView *pageView = [self.pageViews objectAtIndex:page];
if ((NSNull*)pageView == [NSNull null]) {
CGRect frame = self.scrollView.bounds;
//frame.size.width = 280.0f;
frame.size.height = self.scrollView.bounds.size.height;
float offset=20;
frame.size.width = frame.size.width-(2*offset);
frame.origin.x = (326 * page)+offset;
frame.origin.y = 0;
UITableView *tableStage = [[UITableView alloc]initWithFrame:frame];
tableStage.backgroundColor = [UIColor colorWithRed:(250/255.0) green:(248/255.0) blue:(247/255.0) alpha:100];
tableStage.contentMode = UIViewContentModeScaleAspectFit;
tableStage.delegate = self;
tableStage.dataSource = self;
tableStage.tag = page;
tableStage.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollView addSubview:tableStage];
[self.pageViews replaceObjectAtIndex:page withObject:tableStage];
}
}
Now I want that user can jump to a certain UITableview from another UIViewController. Therefore I have a variable pageNumber. When I set the pageNumber I call a method jumpToPage3 and I give the pageNumber with it. This is how the function looks like.
-(void)jumpToPage3:(NSNumber *)page{
NSLog(#"jump to page 3");
float offset=30;
float height = self.scrollView.bounds.size.height;
float width = 320 - (2*offset);
int pagee = [page intValue] - 1;
float x = (320 * pagee) + offset;
[self.scrollView scrollRectToVisible:CGRectMake(x, 0, width , height) animated:NO];
}
The problem is that it is not jumping to the correct page. It stays on the first page.
Can someone help me with this?
When you add content to the scroll view you also have to tell increase the contentSize
How do you make a menu like in Cut the Rope game. Image below:
I am able to make three images slide horizontally but failed to make it as a button.
Though I don't need it to be fancy as the game's, but just a simple button.
Do I need to stack three different Views with its respective buttons inside UIScrollView? I am leaning towards doing it programmatically though.
Code: http://pastebin.com/ikrJ1U7w
Its actually a UIScrollView which containing UIButton of custom type & has image on that. Below that is UIPageIndicator.
You can create it as below, althouh also search for
How to create UIButton programatically to add on scrollview
In your view controller,
In viewDidLoad, in scrollView add the buttons.
UIScrollView *scrollView = // initalize & set frame as per ur req
scrollView.userInteractionEnabled = YES;
scrollView.pagingEnabled = YES;
float x = 0.0;
float y = 0.0, width = 320.0;
float height;
for (int j = 0; j <= numberofpagesYouwant; j++)
{
CGRect frame;
UIButton *button = // Create a button at here;
frame = CGRectMake(x, y, width, height); // Use this as your button frame
[scrollView addSubview:button];
[button release];
x = x + width;
}
scrollView.contentSize = CGSizeMake(numberOfPagesYouHave * 320, heightOfYourScrollView);
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(page != activityIndicator.currentPage)
{
NSLog(#"now page change:%d",page);
[self changePageIndicator:page];
}
}
-(void)changePageIndicator:(int)index
{
activityIndicator.currentPage = index;
}
- (void)setNumberOfPages:(int)numPages1
{
activityIndicator.numberOfPages = numPages1;
}
Yes, I am pretty sure this is just several buttons placed on top of some sort of a scrollView. (most likely done programatically).
I am getting a Exc_Bad_Access error in main when I try to scroll my UIScrollView. This program is simple. I have A UIViewController added in AppDelegate. Then, here is the code in the ViewController. This works fine for scrolling but as soon as I add tmpScrollView.delegate = self. The program won't scroll or zoom and gives me the Exc_Bad_Access error when I try to zoom.
#interface MainViewController : UIViewController <UIScrollViewDelegate>
#property (nonatomic,retain) UIScrollView *tmpScrollView;
#property (nonatomic,retain) UIView *containerView;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tmpScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
tmpScrollView.delegate = self;
[self.view addSubview:tmpScrollView];
// Set up the container view to hold our custom view hierarchy
CGSize containerSize = CGSizeMake(640.0f, 640.0f);
self.containerView = [[UIView alloc] initWithFrame:(CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=containerSize}];
[self.tmpScrollView addSubview:self.containerView];
// Set up custom view hierarchy
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 640.0f, 80.0f)];
redView.backgroundColor = [UIColor redColor];
[self.containerView addSubview:redView];
UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 560.0f, 640.0f, 80.0f)];
blueView.backgroundColor = [UIColor blueColor];
[self.containerView addSubview:blueView];
UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 160.0f, 320.0f, 320.0f)];
greenView.backgroundColor = [UIColor greenColor];
[self.containerView addSubview:greenView];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"slow.png"]];
imageView.center = CGPointMake(320.0f, 320.0f);
[self.containerView addSubview:imageView];
//Tell the scroll view the size of the contents
self.tmpScrollView.contentSize = containerSize;
}
-(void)viewWillAppear:(BOOL)animated
{
NSLog(#"Will Appear");
[super viewWillAppear:animated];
// Set up the minimum & maximum zoom scales
CGRect scrollViewFrame = self.tmpScrollView.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / self.tmpScrollView.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / self.tmpScrollView.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);
self.tmpScrollView.minimumZoomScale = minScale;
self.tmpScrollView.maximumZoomScale = 1.0f;
self.tmpScrollView.zoomScale = minScale;
//***** Here is the line for setting the delegate
self.tmpScrollView.delegate = self;
[self centerScrollViewContents];
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
NSLog(#"End Zoom");
}
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
// Return the view that we want to zoom
return self.containerView;
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
// The scroll view has zoomed, so we need to re-center the contents
[self centerScrollViewContents];
}
#end
Thanks for any help. This has been driving me crazy for a day now...
Edit: Adding centerScrollViewContens too:
- (void)centerScrollViewContents {
CGSize boundsSize = self.tmpScrollView.bounds.size;
CGRect contentsFrame = self.containerView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.containerView.frame = contentsFrame;
}
Whatever Code you have provided is working fine on my end.May be there could be some sort of problem in your "centerScrollViewContents" method.Can you post the code for this method also???
You need to work out the minimum zoom scale for the scroll view. A zoom scale of one means that the content is displayed at normal size. A zoom scale below one shows the content zoomed out, while a zoom scale of greater than one shows the content zoomed in. To get the minimum zoom scale, you calculate how far you’d need to zoom out so that the image fits snugly in your scroll view’s bounds based on its width. Then you do the same based upon the image’s height. The minimum of those two resulting zoom scales will be the scroll view’s minimum zoom scale. That gives you a zoom scale where you can see the entire image when fully zoomed out.
Swift:
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleWidth, scaleHeight);
scrollView.minimumZoomScale = minScale;
Objective-C
CGFloat scrollViewFrame = scrollView.frame
CGFloat scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
CGFloat scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
CGFloat minScale = min(scaleWidth, scaleHeight);
scrollView.minimumZoomScale = minScale;
From other projects and personal experience doing heavy GPU on the iOS (endless scroll, maximum bitmap size, etc), I've noticed that each device has it's own threshold. For past projects, I've also hardcoded the below values as the minimumZoomScale to prevent the crashes:
scale :
{
iPad : {
min : 0.8
, max : 1.6
}
, iPhone : {
min : 0.25
, max : 1.6
}
, iPhone6 : {
min : 0.3333
, max : 1.6
}
, iPhoneResizable: {
min : 1
, max : 1.6
}
}
Great tutorial for beginners: http://www.raywenderlich.com/76436/use-uiscrollview-scroll-zoom-content-swift
I have a custom UIViewController onto which I've added a UIImageView (on the StoryBoard) and then embedded the UIImageView in a UIScrollView. My program loads an image into the imageView and scales it to properly fit. By proper fit, I mean this:
if the aspect ratio of the image exactly matches that of the view, the image will be scaled to exactly fit the view, with no scroll bars
otherwise, the image will be scaled to exactly fit in one dimension, with a scrollbar in the other dimension.
I currently do this in viewWillAppear. Below is my code for that method and an auxiliary method that calculates the correct zoomScale:
-(float) findZoomScale {
float widthRatio = self.view.bounds.size.width / self.imageView.image.size.width;
float heightRatio = self.view.bounds.size.height / self.imageView.image.size.height;
float ratio;
if (widthRatio > heightRatio) ratio = widthRatio;
else ratio = heightRatio;
return ratio;
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
self.imageView.image = self.image;
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
self.scrollView.contentSize = self.imageView.image.size;
self.scrollView.zoomScale = [self findZoomScale];
[self.scrollView flashScrollIndicators];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.photoURL]];
self.imageView.image = self.image;
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width,
self.imageView.image.size.height);
self.scrollView.delegate = self;
self.scrollView.zoomScale = 1.0;
self.navigationItem.title = self.photoTitle;
self.scrollView.autoresizesSubviews = YES;
self.scrollView.autoresizingMask = (UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
}
This code works as I intended for the initial load of an image, whether the iPhone is in landscape or portrait orientation. But when I then rotate the iPhone with the image already loaded, it does not properly rescale. I have tried to do the rescaling in didRotateFromInterfaceOrientation, playing with the scrollView's zoomScale property, but I can't get it to work. Is this the correct place to do the rescaling? And if so, how do I do it? Thanks.
Duane
I just had this exact problem (I assume you're on the CS193p assignment 4 as well), and solved it by setting the zoomScale back to 1 before adjusting the UIScrollView's contentSize upon rotation.
For example:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//reset zoomScale back to 1 so that contentSize can be modified correctly
self.scrollView.zoomScale = 1;
// reset scrolling area equal to size of image
self.scrollView.contentSize = self.imageView.image.size;
//reset the image frame to the size of the image
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
//set the zoomScale to what we actually want
self.scrollView.zoomScale = [self findZoomScale];
}
You can use
-(void)viewWillLayoutSubviews
in your UIViewController. This will get called whenever the view is loaded/rotated/resized.
I need to create a horizontal UIScrollView which to hold hundreds of thumbnail images, just like a slide of thumbnails.
For example, there will be 10 thumbnails showing in a single screen, each of them are horizontally adjacent to each other.
My problem is that I don't know how to make a horizontal UIScrollView to hold the multiple thumbnails which showing at the same time ?
A sample photo is as below. See the bottom part of the screen.
Thanks.
You can add all the thumbnails programatically to your scrollview and use the setContentSize method of UIScrollView. you have to pass 2 values in contentOffset. 1 for width and 1 for height. Please follow link to explore more on this. If you need further help please leave a comment.
Hope it helps.
Please consider Following example.
- (void)setupHorizontalScrollView
{
scrollView.delegate = self;
[self.scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = NO;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
NSInteger tot=0;
CGFloat cx = 0;
for (; ; nimages++) {
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (tot==15) {
break;
}
if (4==nimages) {
nimages=0;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = 40;
rect.size.width = 40;
rect.origin.x = cx;
rect.origin.y = 0;
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += imageView.frame.size.width+5;
tot++;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
I suggest you to look at nimbus
Check out bjhomer's HSImageSidebarView project. It lets you load a scrollview horizontally or vertically and load in the images. Super easy to implement.
First of all, at storyboard drag and drop the scroll view and make the outlet of scrollview named scrollView. Two array one is mutable and one is immutable.
#property(nonatomic,strong)IBOutlet UIScrollView *scrollView;
#property(nonatomic,strong)NSMutableArray *images;
#property(nonatomic,strong)NSArray *imagesName;
The immutable array only store the images which we want to show on the scroll view.Make sure UIscrollview delegate is defined.
In viewcontoller.m file in didload function do following code:
imagesName = [[NSArray alloc]initWithObjects:#"centipede.jpg",#"ladybug.jpg",#"potatoBug.jpg",#"wolfSpider.jpg", #"ladybug.jpg",#"potatoBug.jpg",#"centipede.jpg",#"wolfSpider.jpg",nil];
// mutable array used to show the images on scrollview dynamic becaus after one
// image when scroll other will come
images = [[NSMutableArray alloc]init];
scrollView.delegate = self;
scrollView.scrollEnabled = YES;
int scrollWidth = 120;
scrollView.contentSize = CGSizeMake(scrollWidth,80);
int xOffset = 0;
//the loop go till all images will load
for(int index=0; index < [imagesName count]; index++)
{
UIImageView *img = [[UIImageView alloc] init];
// make the imageview object because in scrollview we need image
img.frame = CGRectMake(5+xOffset, 0, 160, 110);
// the offset represent the values, used so that topleft for each image will
// change with(5+xOffset, 0)and the bottomright(160, 110)
NSLog(#"image: %#",[imagesName objectAtIndex:index]);
img.image = [UIImage imageNamed:[imagesName objectAtIndex:index]];
// The image will put on the img object
[images insertObject:img atIndex:index];
// Put the img object at the images array which is mutable array
scrollView.contentSize = CGSizeMake(scrollWidth+xOffset,110);
//scroll view size show after 125 width the scroll view enabled
[scrollView addSubview:[images objectAtIndex:index]];
// set images on scroll view
xOffset += 170;
}
You can calculate content size width of the scrollview as width = number of images * size of each image. Then set contentSize of the scrollview to this width and the height that you want (scrollView.contentSize = CGSizeMake(width, height))