Scroll View adding views on top of each other - objective-c

I can add several scrollviews with its background colours changed and it works fine. So basically for every view you have different background colours. However when I try to add separate views for each of these, it adds it right on top of the other and I don't know why.
UIViewController *view1 = [self.storyboard instantiateViewControllerWithIdentifier:#"View1"];
UIViewController *view2 = [self.storyboard instantiateViewControllerWithIdentifier:#"View2"];
UIViewController *view3 = [self.storyboard instantiateViewControllerWithIdentifier:#"View3"];
for (NSInteger i=0; i<ScrollViewControllerNumberOfPages; i++) {
CGFloat yOrigin = i * self.view.frame.size.height;
CGRect subViewFrame = CGRectMake(yOrigin, 0, pageHeight, pageWidth);
NSLog(#"Printing Width and Height %f %f",pageWidth,pageHeight);
UIView *subView = [[UIView alloc] initWithFrame:subViewFrame];
// Pick a random colour for the view
CGFloat randomRed = ((CGFloat)(arc4random() % 1000))/1000;
CGFloat randomGreen = ((CGFloat)(arc4random() % 1000))/1000;
CGFloat randomBlue = ((CGFloat)(arc4random() % 1000))/1000;
subView.backgroundColor = [UIColor colorWithRed:randomRed green:randomGreen blue:randomBlue alpha:1];
NSLog(#"printin i %i", i);
if (i == 0)
subView = view1.view;
else if (i == 1)
subView = view2.view;
[self.scrollView addSubview:subView];
}

This is kind of a shot in the dark because your code would need some serious rethinking.
What you're doing is you allocate a subview, you modify it's frame and background and then completely disregard this and set it to a view of previously instantiated viewcontoller.
This should work (in a way):
UIViewController *view1 = [self.storyboard instantiateViewControllerWithIdentifier:#"View1"];
UIViewController *view2 = [self.storyboard instantiateViewControllerWithIdentifier:#"View2"];
UIViewController *view3 = [self.storyboard instantiateViewControllerWithIdentifier:#"View3"];
for (NSInteger i=0; i<ScrollViewControllerNumberOfPages; i++) {
CGFloat yOrigin = i * self.view.frame.size.height;
CGRect subViewFrame = CGRectMake(yOrigin, 0, pageHeight, pageWidth);
NSLog(#"Printing Width and Height %f %f",pageWidth,pageHeight);
UIView *subView;
if (i == 0)
subView = view1.view;
else if (i == 1)
subView = view2.view;
subView.frame = subViewFrame;
// Pick a random colour for the view
CGFloat randomRed = ((CGFloat)(arc4random() % 1000))/1000;
CGFloat randomGreen = ((CGFloat)(arc4random() % 1000))/1000;
CGFloat randomBlue = ((CGFloat)(arc4random() % 1000))/1000;
subView.backgroundColor = [UIColor colorWithRed:randomRed green:randomGreen blue:randomBlue alpha:1];
NSLog(#"printin i %d", i);
[self.scrollView addSubview:subView];
}
It might look a bit better if you do it like:
for (NSInteger i=0; i<ScrollViewControllerNumberOfPages; i++) {
CGFloat yOrigin = i * self.view.frame.size.height;
CGRect subViewFrame = CGRectMake(yOrigin, 0, pageHeight, pageWidth);
NSLog(#"Printing Width and Height %f %f",pageWidth,pageHeight);
UIViewController *subViewCont = [self.storyboard instantiateViewControllerWithIdentifier:[NSString stringWithFormat:#"View%d",i+1]];
UIView *subView = subViewCont.view;
subView.frame = subViewFrame;
// Pick a random colour for the view
CGFloat randomRed = ((CGFloat)(arc4random() % 1000))/1000;
CGFloat randomGreen = ((CGFloat)(arc4random() % 1000))/1000;
CGFloat randomBlue = ((CGFloat)(arc4random() % 1000))/1000;
subView.backgroundColor = [UIColor colorWithRed:randomRed green:randomGreen blue:randomBlue alpha:1];
NSLog(#"printin i %d", i);
[self.scrollView addSubview:subView];
}

Related

Center row of Buttons in UIScrollView

I am adding buttons in a UIScrollView dynamically, but some views only have two buttons and some have 10. I want to center the buttons in the scroll view so It doesn't look like I built them from the left to right. I've tried several tricks from SO and nothing seems to work. setting the content offset was my first approach, but doesn't have the effect I want.
Here is the code I am using:
- (void)addButton:(UIButton *)button {
CGFloat contentWidth = 0.0f;
CGRect buttonFrame = button.frame;
if ([_scrollView.subviews count] == 0) {
buttonFrame.origin.x = self.contentIndicatorWidth + kButtonSeperator;
contentWidth = self.contentIndicatorWidth + buttonFrame.size.width + self.contentIndicatorWidth;
} else {
contentWidth = _scrollView.contentSize.width;
UIButton *lastButton = [_scrollView.subviews lastObject];
buttonFrame.origin.x = lastButton.frame.origin.x + lastButton.frame.size.width + kButtonSeperator;
contentWidth += buttonFrame.size.width + kButtonSeperator;
}
button.frame = buttonFrame;
[_scrollView addSubview:button];
_scrollView.contentSize = CGSizeMake(contentWidth *kContentMultiplicityFactor, _scrollView.frame.size.height);
[_buttons setValue:button forKey:button.titleLabel.text];
totalWidth = contentWidth;
// [_scrollView scrollRectToVisible:[self getButtonAtIndex:0].frame animated:YES];
}
After you add the buttons call this method:
- (void)centerButtons:(NSArray*)buttons {
CGSize scrollViewSize = _scrollView.bounds.size;
// Measure the total width taken by the buttons
CGFloat width = 0;
for (UIButton* b in buttons)
width += b.bounds.size.width + kButtonSeparator;
if (width > kButtonSeparator)
width -= kButtonSeparator;
// If the buttons width is shorter than the visible bounds, adjust origin
CGFloat origin = 0;
if (width < scrollViewSize.width)
origin = (scrollViewSize.width - width) / 2.f;
// Place buttons
CGFloat x = origin;
CGFloat y = 0;
for (UIButton* b in buttons) {
b.center = CGPointMake(x + b.bounds.size.width/2.f, y + b.bounds.size.height/2.f);
x += b.bounds.size.width + kButtonSeparator;
}
_scrollView.contentSize = CGSizeMake(MAX(scrollViewSize.width, width), scrollViewSize.height);
}
In the end, this isn't a very hard problem. I guess you add these buttons on the fly.
You have a scrollview called ScrollView and you have already put in content size.
So you have 10 buttons of different widths :
int btnCount = 10;
int totalWidth = 0;
int spacing = 5;
NSMUtableArray *buttons = [[NSMutableArray alloc] init];
for (int i=0; i<btnCount-1; i++) {
UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[b setTitle:#"some title" forState:UIControlStateNormal];
[b sizeToFit];
CGRect frame = b.frame;
totalWidth += b.frame.size.width;
[buttons addObject:b];
}
totalWidth += (btnCount * spacing);
UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, totalWidth, 40)];
int priorButtonX = 0;
for (UIButton *b in buttons) {
CGRect frame = b.frame;
frame.origin.x = priorButtonX;
b.frame = frame;
priorButtonX = frame.origin.x + spacing;
[btnView addSubview:b];
}
int scrollSizeWidth = scrollView.contentSize.width;
int placeX = (scrollSizeWidth /2) - (btnView.frame.size.width /2)
CGRect btnViewFrame = btnView.frame;
btnViewFrame.origin.x = placeX;
bbtnView.frame = btnViewFrame;
[scrollView addSubView:btnView];
You might want to do something with Y placement, but that one is very simple. This code can be written in fewer lines, and use fewer variables, but this is done to make it easier to read.

Place UIImageViews in row

I am looping through a array and adding UIImageViews, the array has a have different count depending on somethings. So the amount of UIImageViews varies. What I need to do is line them up in a row in the center of the view. I know the code that I need to use its the calculations that I am having an issue with.
for (int i = 0; i < [_lettersArray count]; i++){
UIImage* imageContainer = [UIImage imageNamed:#"container.png"];
UIImageView *containerView = [[UIImageView alloc] initWithImage:imageContainer];
containerView.frame = CGRectMake(???,120,imageContainer.size.width,imageContainer.size.height);
[self.view addSubview:containerView];
}
[self _layoutViews:self.imageViews inView:self.view];
- (void) _layoutViews:(NSArray *)views inView:(UIView *)contentView
{
NSInteger overallWidth = 0;
for ( UIView *view in views ) {
overallWidth += view.frame.size.width;
}
CGSize contentSize = contentView.frame.size;
CGFloat startOffset = (contentSize.width - overallWidth)/2.0;
CGFloat offset = startOffset;
for ( UIView *view in views ) {
CGRect frame = view.frame;
frame.origin.x = offset;
frame.origin.y = (contentSize.height/2.0) - (frame.size.height/2.0);
view.frame = frame;
offset += view.frame.size.width;
}
}
For your example code it would be something like this:
CGFloat count = [_lettersArray count];
NSMutableArray *imageViews = [[NSMutableArray alloc] initWithCapacity:count];
for (int i = 0; i < [_lettersArray count]; i++) {
UIImage *imageContainer = [UIImage imageNamed:#"container.png"];
UIImageView *containerView = [[UIImageView alloc] initWithImage:imageContainer];
containerView.frame = CGRectMake(0,120,imageContainer.size.width,imageContainer.size.height);
[imageViews addObject:containerView];
[self.view addSubview:containerView];
}
[self _horizontalCenterViews:imageViews inView:self.view];
return YES;
}
- (void) _horizontalCenterViews:(NSArray *)views inView:(UIView *)contentView
{
NSInteger overallWidth = 0;
for ( UIView *view in views ) {
overallWidth += view.frame.size.width;
}
CGSize contentSize = contentView.frame.size;
CGFloat startOffset = (contentSize.width - overallWidth)/2.0;
CGFloat offset = startOffset;
for ( UIView *view in views ) {
CGRect frame = view.frame;
frame.origin.x = offset;
view.frame = frame;
offset += view.frame.size.width;
}
}

space between images in thumbnail for ipad

I create Thumbnail photo with scrollview for ipad, here is the code:
// load all the images from bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
}
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
}
rightnow I have all images in UIScrollView that they are next to each other, I want to have some space between each images like this picture
would you please give me some hint that how can I add space between these images?
Thanks in Advance!
Try this:
curXLoc += (kScrollObjWidth) + kDifferenceBetweenImages;
and define kDifferenceBeteweenIMages accordingly.
Use UICollectionView instead. Much easier to achieve what you want and will work better too.
It even has a property for the space between each cell.
Try this one :
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
frame.size.height = //put height;
frame.size.width = //put width;
frame.origin.y = //put y;
view.frame = frame;
curXLoc += (kScrollObjWidth) + 15;

Why images are not showing in UIScrollView?

I am using this code to show scrolling images but I am only getting a white screen. I drag drop uiscrollview, created the iboutlet, synthesized it and rest of the code is here
#synthesize scrollView1;
const CGFloat kScrollObjHeight = 199.0;
const CGFloat kScrollObjWidth = 280.0;
const NSUInteger kNumImages = 5;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
// set the content size so it can be scrollable
[scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
scrollView1 = [[UIScrollView alloc]init];
bgArray = [NSArray arrayWithObjects:#"Bg", #"Bg1.png", #"Bg2.png", #"Bg3.png", #"Bg4.png", #"Bg5.png", #"Bg6.png", #"Bg7.png", #"Bg8.png", nil];
[scrollView1 setBackgroundColor:[UIColor blackColor]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView1.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollView1.scrollEnabled = YES;
// pagingEnabled property default is NO, if set the scroller will stop or snap at each photo
// if you want free-flowing scroll, don't set this property.
scrollView1.pagingEnabled = YES;
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 0; i < [bgArray count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#", [bgArray objectAtIndex:i]];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = 199.0;
rect.size.width = 280.0;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView1 addSubview:imageView];
[scrollView1 setShowsHorizontalScrollIndicator:NO];
[scrollView1 setShowsVerticalScrollIndicator:NO];
}
[self layoutScrollImages];
}
I think if you are create UIScrollView from code
scrollView1 = [[UIScrollView alloc]init];
then please add the scrollView1 in view
Example:-[self.view addSubview:scrollView1];
if you are create UIScrollView from nib then
not use this code
scrollView1 = [[UIScrollView alloc]init];
solve your probem

Issue with scroll view and accessing its subviews

I have a scroll view that contains image view sized 68x78:
As you could see, all that images except from the centered one have a shadow. It changes when user scrolls, center image is always clear. It goes perfect until for the left edge image:
Here is the code:
-(void) buildSlideView{
fotosJugadores = [[NSArray alloc] initWithObjects:#"cara5.png", #"cara7.png", #"cara8.png", #"cara9.png", #"cara11.png", #"cara13.png", #"cara14.png", #"cara15.png", #"cara18.png",#"cara19.png", #"cara20.png", #"cara32.png",#"cara44.png",#"cara51.png", #"cara100.png", #"cara101.png", #"cara102.png",#"cara103.png", #"cara104.png", #"cara105.png",#"cara106.png",#"cara107.png", nil];
numberOfViews = [fotosJugadores count];
for (int i = 0; i < [fotosJugadores count]; i++) {
UIImage *myImage = [UIImage imageNamed:[fotosJugadores objectAtIndex:i]];
CGFloat yOrigin = i * (myImage.size.width+3) + 120;
UIImageView *awesomeView = [[UIImageView alloc] initWithFrame:CGRectMake(yOrigin, 0, myImage.size.width, myImage.size.height)];
awesomeView.tag = i;
awesomeView.image = myImage;
awesomeView.alpha = 0.5f;
awesomeView.backgroundColor = [UIColor blackColor];
[self.jugadorSlide addSubview:awesomeView];
awesomeView=nil;
}
[jugadorSlide setBackgroundColor:[UIColor blackColor]];
jugadorSlide.contentSize = CGSizeMake(68 * numberOfViews+240,78);
jugadorSlide.layer.cornerRadius = 11;
jugadorSlide.layer.masksToBounds = YES;
[jugadorSlide setContentOffset:CGPointMake(((68 * numberOfViews)/2), 0)];
//jugadorSlide.decelerationRate = UIScrollViewDecelerationRateNormal;
[self scrollViewDidEndDragging:jugadorSlide willDecelerate:NO];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
currentIndex = roundf(scrollView.contentOffset.x / 68);
NSLog(#"current end %d", currentIndex);
UIImageView *currentImage = [scrollView viewWithTag:currentIndex];
if (currentIndex>0&&currentIndex<=21){
if (currentIndex==currentImage.tag){
currentImage.alpha=1.0f;
[self changePerfilImage:currentImage.tag];}
CGPoint pointZero= CGPointMake(scrollView.contentOffset.x, currentImage.frame.origin.y);
[jugadorSlide setContentOffset:pointZero animated:YES];
}else {
UIImageView *currentImage = [scrollView viewWithTag:0];
NSLog(#"end dragging image tag %d", currentImage.tag);
currentImage.alpha=1.0f;
[self changePerfilImage:currentImage.tag];}
CGPoint pointZero= CGPointMake(currentImage.frame.origin.x+15, 0);
//[jugadorSlide setContentOffset:pointZero animated:YES];
}
As you can see, in the scrollViewDidEndDragging: "else" , I forced the tag as a desesperate solution, but images doesn't get clear.
You are incrementing the tag twice...
awesomeView.tag = i++;
Should just be:
awesomeView.tag = i+1;
I use i+1 because I never use a tag of 0 since any subview that hasn't been assigned a tag will have a tag of 0.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
NSInteger currentIndex = roundf(scrollView.contentOffset.x / 68.0) + 1;
UIImageView *currentImage = [scrollView viewWithTag:currentIndex];
...
}
If this doesn't work you should NSLog the currentIndex each time you land on a new image and see what is happening when you land on the first one.