I have a UIViewController. The root UIView contains a custom UIScrollView I'm using for displaying thumbnail images in a grid (ThumbnailGrid class). This grid can contain a lot of UIViews which display images (GridTile class). Because there are so many grid tiles, the user can scroll down the ThumbnailGrid. I want to only load images for grid tiles which the user can actually see, I don't want to load ones for grid tiles which are off the edges of the screen.
How do I determine whether or not one of these GridTile UIViews is being displayed on the screen or not?
I've tried the following but it always seems to return false.
- (bool) isViewDisplayed:(UIView*)view
{
CGRect viewFrame = view.frame;
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
if (CGRectIntersectsRect(viewFrame, appFrame)) return true;
return false;
}
Am I missing something?
Thanks in advance for any help!
EDIT
THE SOLUTION
Turns out the coordinate systems were wrong, so I was getting some strange occurrences where the method should have returned true and instead it returned false, and vice versa.
- (bool) isViewDisplated:(UIView*)view
{
CGRect viewFrame = [parentOfView convertRect:view.frame toView:nil];
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
if (CGRectIntersectsRect(viewFrame, appFrame)) return true;
return false;
}
You also need to convert rect to the correct coordinate system:
- (bool)isViewDisplayed:(UIView*)view
{
if (view.window) {
CGRect viewFrame = [view.window convertRect:view.frame fromView:view.superview];
CGRect screenFrame = view.window.bounds;
return CGRectIntersectsRect(viewFrame, screenFrame);
}
return false;
}
I know it doesn't directly answer your question, but still: why don't you use a UICollectionView? It's able to handle most of the heavy parts for you. You don't have to care about the ones they are outside of the screen. You just to care about the behavior (delegation) and the content (data source).
Honestly, I think you are going about this the wrong way. There are a ton of existing frameworks designed to do exactly this. I don't know if I would spend the time to hand roll my own solution and handle all of the memory and view management. Check out this post: Grid of images in iOS
You could do a compare like this:
NSMutableArray *outArray = [NSMutableArray array];
NSMutableArray *inArray = [NSMutableArray array];
for (UIView *vw in rootView.subViews){
if(vw.frame.origin.x <0 || vw.framew.origin.x >rootView.frame.size.width){
[outArray addObject:vw];
}else if(vw.frame.origin.y <0 || vw.framew.origin.y >rootView.frame.size.height){
[outArray addObject:vw];
}else{
[inArray addObject:vw];
}
}
So in the end your outArray will contain all the views which are partially/fully out of super view and inArray will have all those views which is completely inside the super view.
If you want to check for a single view using a method (say -(bool)isViewDisplayed:(UIView*)vw ), the same code inside the for loop would suffice, only thing is you would have to return true/false instead of adding to an array
PS: If you want to get only views completely out of your super view then instead of comparing against zero check against -vw.frame.size.width & -vw.frame.size.height.
Make use of tags pretty easy to manage.
something like this
UIView *view1 = [UIView]alloc]init];
view1.tag = 1;
[mainView addSubview:view1
];
and to check
UIView *temp = [mainView.view viewWithTag:1];
if(temp!=nil)return YES;
else NO;
see if this helps
Related
I want to display some images in a scroll view, but I am facing some issues.
Here is what I have:
- (void)viewDidLoad
{
[super viewDidLoad];
myObject = [[NSMutableArray alloc] init];
[myObject addObject:#"tut_5.jpg"];
[myObject addObject:#"tut_2.jpg"];
[myObject addObject:#"tut_3.jpg"];
[myObject addObject:#"tut_4.jpg"];
pageControlBeingUsed = NO;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHight = screenRect.size.height;
for (int i = 0; i < [myObject count]; i++) {
CGRect frame;
frame.origin.x = self.takeTourScrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.takeTourScrollView.frame.size;
NSString *val = [myObject objectAtIndex:i];
UIImage* theImage = [UIImage imageNamed:val];
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];
img.image = theImage;
[self.takeTourScrollView addSubview:img];
}
The first first image seems to be ok.
Then when I swipe left I am getting a blank screen
I swipe left again and then I see my second picture. And it goes like that for all the 4 images.
Any ideas what am I doing wrong ?
There are system components that will give you what you want with much less work and a more refined user experience. Using a UICollectionView is one possibility, as mentioned by Vive in her answer. My suggestion would be a UIPageViewController. There is a sample app called PhotoScroller from Apple that shows how to implement a UI very much like what you describe. Do a search in the Xcode docs for "PhotoScroller" to find it.
I'd advise to use UITableView/UICollectionView for such behaviour. You can set the image in each cell and they'll be reused - it will be much better in terms of memory management.
The tableView will by the way place all elements in proper places (you just need to define the height of the cell or the layout).
It will also properly resize on events (eg phone rotation).
Also, you should try to avoid hardcoding the sizes:
CGRectMake(screenWidth*i,0,185 ,284)
You will fail in case of smaller / bigger devices. It'll be a great pain to maintain the code after some time.
-- edit --
After #Duncan C posted his answer, I've noticed you're looking for a paging system. You can go with building your own solution either on UIPageViewController or on UICollectionView. However you can also use third party libraries, I really enjoy this one: https://www.cocoacontrols.com/controls/bwwalkthrough. It has a support of different animations and does a ton of stuff for you :).
you already set the x position of uiscrollview. do not need to set the x postion of UIImageView.Because you used imageview as a subview of uiimagescrollview.
change this line to
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];
with
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,185 ,284)];
I've been looking at the same problem for so long I'm probably missing a simple solution here.
I created a small library to provide a custom UIView that sticks to the keyboard like the one for iMessage does (aka doesn't hide with keyboard): https://github.com/oseparovic/MessageComposerView
Basically the problem I'm experiencing is that when the user init's custom view I want a view with the following default rect initialized:
CGFloat defaultHeight = 44.0;
CGRect frame = CGRectMake(0,
[self currentScreenSize].height-defaultHeight,
[self currentScreenSize].width,
defaultHeight)
This requires that the currentScreenSize is calculated within the UIView. I've tried multiple implementations all of which have their downsides. There doesn't seems to be a good solution due to this breaking principles of MVC.
There are lots of duplicate questions on SO but most assume you have access to the rest of the code base (e.g. the app delegate) which this custom view does not so I'm looking for a self contained solution.
Here are the two leading implementations I'm using:
NextResponder
This solution seems to be fairly successful in a wide variety of scenarios. All it does is get the next responder's frame which very conveniently doesn't include the nav or status bar and can be used to position the UIView at the bottom of the screen.
The main problem is that self.nextResponder within the UIView is nil at the point of initialization, meaning it can't be used (at least not that I know) to set up the initial frame. Once the view has been initialized and added as a subview though this seems to work like a charm for various repositioning uses.
- (CGSize)currentScreenSize {
// return the screen size with respect to the orientation
return ((UIView*)self.nextResponder).frame.size;
}
ApplicationFrame
This was the solution I was using for a long time but it's far more bulky and has several problems. First of all, by using the applicationFrame you have to deal with the nav bar height as it will otherwise offset the position of your view. This means you have to determine if it is visible, get its height and subtract it from your currentSize.
Getting the nav bar unfortunately means you need to access the UINavigationController which is not nearly as simple as accessing the UIViewController. The best solution I've had so far is the below included currentNavigationBarHeight. I recently found an issue though where this will fail to get the nav bar height if a UIAlertView is present as [UIApplication sharedApplication].keyWindow.rootViewController will evaluate to _UIAlertShimPresentingViewController
- (CGSize)currentScreenSize {
// there are a few problems with this implementation. Namely nav bar height
// especially was unreliable. For example when UIAlertView height was present
// we couldn't properly determine the nav bar height. The above method appears to be
// working more consistently. If it doesn't work for you try this method below instead.
return [self currentScreenSizeInInterfaceOrientation:[self currentInterfaceOrientation]];
}
- (CGSize)currentScreenSizeInInterfaceOrientation:(UIInterfaceOrientation)orientation {
// http://stackoverflow.com/a/7905540/740474
// get the size of the application frame (screensize - status bar height)
CGSize size = [UIScreen mainScreen].applicationFrame.size;
// if the orientation at this point is landscape but it hasn't fully rotated yet use landscape size instead.
// handling differs between iOS 7 && 8 so need to check if size is properly configured or not. On
// iOS 7 height will still be greater than width in landscape without this call but on iOS 8
// it won't
if (UIInterfaceOrientationIsLandscape(orientation) && size.height > size.width) {
size = CGSizeMake(size.height, size.width);
}
// subtract the height of the navigation bar from the screen height
size.height -= [self currentNavigationBarHeight];
return size;
}
- (UIInterfaceOrientation)currentInterfaceOrientation {
// Returns the orientation of the Interface NOT the Device. The two do not happen in exact unison so
// this point is important.
return [UIApplication sharedApplication].statusBarOrientation;
}
- (CGFloat)currentNavigationBarHeight {
// TODO this will fail to get the correct height when a UIAlertView is present
id nav = [UIApplication sharedApplication].keyWindow.rootViewController;
if ([nav isKindOfClass:[UINavigationController class]]) {
UINavigationController *navc = (UINavigationController *) nav;
if(navc.navigationBarHidden) {
return 0;
} else {
return navc.navigationBar.frame.size.height;
}
}
return 0;
}
Does anyone have suggestion about how I can best calculate the UIViewController size from within this UIView. I'm totally open to other suggestions on how to stick the UIView to the bottom of the screen upon initialization that I may have overlooked. Thank you!
+ (id) getCurrentUIViewController : (id)res {
if([res isKindOfClass:[UIViewController class]]) {
return res;
}
else if ([res isKindOfClass:[UIView class]]) {
return [Function getCurrentUIViewController:[res nextResponder]];
}
else {
return nil;
}
}
For the tutorial for my app, I am trying to create a UILabel that drifts across the displayed screen when a view appears and then is destroyed so that if the user comes back to that view during the tutorial, the UILabel will be created anew and again drift across the page. Here's a sample of one of the custom view controllers I am displaying with my UIPageViewController:
//this is just a custom UILabel with some padding
#property (nonatomic) PaddedLabel *directionsLabel;
//I have tried setting UILabel to nil or removing it from view
-(void)viewWillDisappear:(BOOL)animated
{
NSLog(#"view is disappearing");
//this does not remove the label
self.directionsLabel = nil;
//nor does this
[self.directionsLabel removeFromSuperview];
}
- (void)viewDidAppear:(BOOL)animated
{
[self messageTutorial];
}
- (void)messageTutorial
{
CGFloat width = [[UIScreen mainScreen] bounds].size.width;
CGFloat height = [[UIScreen mainScreen] bounds].size.height;
PaddedLabel *directionsLabel = [[PaddedLabel alloc] initWithFrame:CGRectMake(_width/2, _height/2, 100, 100)];
directionsLabel.text = #"test";
CGRect f = directionsLabel.frame;
f.size = size;
directionsLabel.frame = f;
directionsLabel.center = self.view.center;
f = directionsLabel.frame;
f = directionsLabel.frame;
f.origin.y = .1*height;
directionsLabel.frame = f;
[self.view addSubview:directionsLabel];
[UIView animateWithDuration:TUTORIAL_DISAPPEAR_TIME animations:^{
directionsLabel.alpha = .5;
CGRect f = directionsLabel.frame;
f.origin.y = height - f.size.height*1.4;
directionsLabel.frame = f;
NSLog(#"animating");
} completion:^(BOOL finished) {
[directionsLabel removeFromSuperview];
//this also doesn't actually remove the label
}];
}
The problem is that if the user pages back to see this view she now sees a new label and the old one, so that if you page back and forth back and forth you end up with many many labels all saying the same thing, in different stages of progressing across the screen.
How can I remove the UILabel when the view disappears and add/create a new one when the view appears/reappears?
Thank you.
The code in your viewWillDisappear method is backwards. You need:
- (void)viewWillDisappear:(BOOL)animated {
NSLog(#"view is disappearing");
[self.directionsLabel removeFromSuperview];
self.directionsLabel = nil;
}
As you had it, setting self.directionsLabel to nil before trying to remove it results in a no-op.
Also, be sure to set self.directionsLabel when you create the label.
Instead of setting your label to nil and effectively destroying the label object (assuming automatic reference counting is on) rather use the following method to hide and show the label as and when your need it.
[self.directionsLabel setHidden:YES]; // hides it
[self.directionsLabel setHidden:NO]; // shows it
You've got the right idea setting objects you're not using to nil and removing them from the super view but it's over kill. A UILabel object uses a negligible amount of memory and you're better off creating the object once and then changing it's properties as you need to.
You don't seem to be setting self.directionsLabel to anything when you create the directionsLabel inside the messageTutorial method. It is a local instance of the label there. You should set it in the method somewhere.
Afterwards, removing it from the superview in viewWillDisappear will work (tested to verify).
Trying to get around a crash that is happening on some iOS devices, in conjunction with advice from Apple to "not cause allocation spikes". How can I change this code to not happen all at once?
for (Item *item in self.items) {
ItemView *itemView = [[ItemView alloc] initWithFrame:CGRectMake(xPos, kYItemOffsetIphone, kItemWidthIphone, kItemHeightIphone) ];
itemView.delegate = self;
[itemView layoutWithData:item]; //this just adds an imageView and button
[self.scrollView addSubview:itemView];
xPos += kXItemSpacingIphone;
}
There are around 20 objects in the self.items array, which are used to build the 20 ItemViews. Again, is there some way to make this code less "allocation intensive"?
I personally do something along the lines of:
Make my view controller the delegate of the scroll view (if you do this in code, you have to modify your view controller's .h to say that it conforms to UIScrollViewDelegate).
Define a scrollViewDidScroll method that (a) determines the frame of the visible portion of the scroll view; (b) determine which of the subviews intersect with that visible portion; (c) load the items that are visible, and unload the ones that aren't.
So, for example, it might look something like the following:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// Determine the frame of the visible portion of the scrollview.
CGRect visibleScrollViewFrame = scrollView.bounds;
visibleScrollViewFrame.origin = scrollView.contentOffset;
// Now iterate through the various items, remove the ones that are not visible,
// and show the ones that are.
for (Item *itemObject in self.itemCollection)
{
// Determine the frame within the scrollview that the object does (or
// should) occupy.
CGRect itemObjectFrame = [self getItemObjectFrame:itemObject];
// see if those two frames intersect
if (CGRectIntersectsRect(visibleScrollViewFrame, itemObjectFrame))
{
// If it's visible, then load it (if it's not already).
// Personally, I have my object have a boolean property that
// tells me whether it's loaded or not. You can do this any
// way you want.
if (!itemObject.loaded)
[itemObject loadItem];
}
else
{
// If not, go ahead and unload it (if it's loaded) to conserve memory.
if (itemObject.loaded)
[itemObject unloadItem];
}
}
}
That's the basic idea. You can certainly optimize this logic based upon your app's particular design, but this is how I generally do it.
I would like to implement an app using a UIScrollView with paging, similar to the apple weather app.
But I am a little concerned about performance. The example implementation I have been using loads all of the views then the application launches. After a certain point, once this prove slow?
I wonder how Apple's camera roll is dealing with this, where a user may have 100+ photos that can be scrolled through. Should I try to figure out a way to build the view only when it is needed? Or maybe there is a way to replicate the dequeue reusable cell technique from a UITableView, only for horizontal view loading, since each view will have the same layout.
By far the most efficient solution (and this is used in many photo-browsing apps such as Facebook, and probably the native Photos app too) is going to be to load the content on-demand, just as UITableView does. Apple's StreetScroller sample project should get you on the right track.
A very efficient solution, is to make sure to reuse any views whenever possible. If you are going to be simply displaying images, you could use a subclass of UIScrollView, and layout these reusable views within layoutSubviews. Here you could detect what views are visible and not visible and create the subviews as needed.
An example dequeuing function may look like:
- (UIImageView *)dequeueReusableTileWithFrame:(CGRect) frame andImage:(UIImage *) image
{
UIImageView *tile = [reusableTiles anyObject];
if (tile) {
[reusableTiles removeObject:tile];
tile.frame = frame;
}
else {
tile = [[UIImageView alloc] initWithFrame:frame];
}
tile.image = image;
return tile;
}
Where reusableTiles is just an iVar of NSMutableSet type. You could then use this to load fetch any currently offscreen image views and quickly and easily bring them back into view.
Your layoutSubviews may look something like:
- (void)layoutSubviews {
[super layoutSubviews];
CGRect visibleBounds = [self bounds];
CGPoint contentArea = [self contentOffset];
//recycle all tiles that are not visible
for (GSVLineTileView *tile in [self subviews]) {
if (! CGRectIntersectsRect([tile frame], visibleBounds)) {
[reusableTiles addObject:tile];
[tile removeFromSuperview];
}
}
int col = firstVisibleColumn = floorf(CGRectGetMinX(visibleBounds)/tileSize.width);
lastVisibleColumn = floorf(CGRectGetMaxX(visibleBounds)/tileSize.width) ;
int row = firstVisibleRow = floorf(CGRectGetMinY(visibleBounds)/tileSize.height);
lastVisibleRow = floorf(CGRectGetMaxY(visibleBounds)/tileSize.height);
while(row <= lastVisibleRow)
{
col = firstVisibleColumn;
while (col <= lastVisibleColumn)
{
if(row < firstDisplayedRow || row > lastDisplayedRow || col < firstDisplayedColumn || col >lastDisplayedColumn)
{
UImageView* tile = [self dequeueReusableTileWithFrame:CGRectMake(tileSize.width*col, tileSize.height*row, tileSize.width, tileSize.height) andImage:YourImage];
[self addSubview:tile];
}
++col;
}
++row;
}
firstDisplayedColumn = firstVisibleColumn;
lastDisplayedColumn = lastVisibleColumn;
firstDisplayedRow = firstVisibleRow;
lastDisplayedRow = lastVisibleRow;
}
I used something similar to this to tile in areas of a line when I was working with an exceptionally large area of a scroll view and it seemed to work quite well. Sorry for any typos that I may have created when updating this for an image view instead of my custom tileView class.