iPhone: How to scroll random height UIView in ScrollView? - iphone

I have ScrollView and UIView created in interface builder (but can as well be code). I want to add random amount of thumbnails (subviews) to UIView and be able to scroll it up-down if there are more than the screen can take. Hovewer, I can't get ScrollView to scroll.
Where and how do I resize UIView and add it as a subview of ScrollView?
When do I set contentSize of scrollView to make it expand along with uiview? I tried creating fixed large contentSize but didn't work as well.
What properties in IB I might need to change to make it work?
I'd like to make the images in uiview clickable in next step.
I guess I could also make both view in code without IB. Just somehow can't get it to work.
Thanks in advance !

//declare base view
UIViewController *viewForLoadForm =[[UIViewController alloc] init];
viewForLoadForm.view.frame=CGRectMake(0, 0,screenSize.size.width,screenSize.size.height);
viewForLoadForm.view.backgroundColor=[UIColor blackColor];
[Manview.view addSubview:viewForLoadForm];
//declare scrollview and add to base view
UIScrollView *scrollview=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenSize.size.width,screenSize.size.height)];
scrollview.indicatorStyle=UIScrollViewIndicatorStyleBlack;
[scrollview setContentSize:CGSizeMake(screenSize.size.width,screenSize.size.height)];
scrollview.clipsToBounds = NO;
scrollview.scrollEnabled = YES;
scrollview.pagingEnabled = NO; scrollview.showsVerticalScrollIndicator =NO;
scrollview.alwaysBounceVertical= YES;
[viewForLoadForm.view addSubview:scrollview];
//Add your controls to scrollview that s image view or something which is needed to display
.........your control's code (textbox,imageview etc)
//took last control's y postion and set your K
float k=Last control's y position +100;(some thing which ll be decide scroll size)
// reassign the scrollview height
[scrollview setContentSize:CGSizeMake(screenSize.size.width,k)];
use above line for scroll view size adjustment at run time.
screenSize.size.width is 320 here

code snippet,
- (void) createThumbView
{
float y_axis = Set y axis;
int x = 0;
int totalImgs = total images;
int tempCnt = 0;
for (int i = 0; i < totalImgs;)
{
float x_axis = set x axis;
int loopCount = 0;
if (totalImgs - tempCnt >= (no of images in row))
{
loopCount = (no of images in row);
}
else
{
loopCount = totalImgs % (no of images in row);
}
for (int j = 0; j < loopCount; j++)
{
MasksData *mData = [masksList objectAtIndex:x];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(x_axis, y_axis, width, height);
[btn setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#.png",mData.bgImage]] forState:UIControlStateNormal];
btn.backgroundColor = [UIColor clearColor];
btn.tag = x;
[scroll View addSubview:btn];
//photoCount++;
x_axis += width + some space;
tempCnt++;
i++;
x++;
}
y_axis += height + some space;
scroll View.contentSize = CGSizeMake(320.0, y_axis);
}
}

Related

UIScrollView + UIPageControl + UIButton

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).

iPhone SDK: UIButtons in UIScrollView - Resize Scroll View to Fit all Non Hidden Buttons

I have 7 UIButtons in a UIScrollView. The top 3 UIButtons can be either hidden or visible depending on if statements in code. Meaning there are 8 possibilities of the 3 UIButtons displaying.
The problem i'm having is getting the UIScrollView to adjust its content size so that there are no "empty" looking spaces in it. For example if the middle UIButton is hidden but the ones above and below it are visible, there is an empty space left.
Is there any way make all the buttons fit one underneath the other in the scrollview without any gaps?
I have tried this code but it didn't work:
if([[facilities objectAtIndex:0]intValue] == 1) {
facilitiesButton.hidden = NO;
}
if([[ListingsEnabled objectAtIndex:0]intValue]==1) {
ListingsBtn.hidden = NO;
}
if([[OffersEnabled objectAtIndex:0]intValue]==1) {
OffersBtn.hidden = NO;
}
CGFloat scrollViewHeight = 0.0f;
self.DetailScrollView.showsHorizontalScrollIndicator = NO;
self.DetailScrollView.showsVerticalScrollIndicator = NO;
for (UIView* view in self.DetailScrollView.subviews)
{
if (!view.hidden)
{
CGFloat y = view.frame.origin.y;
CGFloat h = view.frame.size.height;
if (y + h > scrollViewHeight)
{
scrollViewHeight = h + y;
}
}
}
self.DetailScrollView.showsHorizontalScrollIndicator = YES;
self.DetailScrollView.showsVerticalScrollIndicator = YES;
[self.DetailScrollView setContentSize:(CGSizeMake(self.DetailScrollView.frame.size.width, scrollViewHeight))];
as #Andy commented, you need to position the actual buttons, not just change the scroll view size. A Table View may be indeed the way to go, but for 7 buttons that may be overkill. Here's a snippet that will loop through the buttons and update their positions based on visibility. I omitted the scroll view because it doesn't seem necessary, but if you need them in a scroll view that will update i can edit the code, just let me know.
/////////////////////
///// USES ARC //////
/////////////////////
- (void)viewDidLoad
{
[super viewDidLoad];
allButtons = [NSMutableArray array];
// Create 7 buttons and randomly hide some
for (int i = 0; i < 7; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 0, 100, 50);
[button setTitle:[NSString stringWithFormat:#"Button %i", i+1] forState:UIControlStateNormal];
[button addTarget:self action:#selector(randomizeButtons:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button.hidden = arc4random_uniform(2)-1 > 0;
[allButtons addObject:button];
}
[self updateButtonLayout];
}
-(void)updateButtonLayout
{
// position buttons based on visiblity
CGRect lastButtonFrame = CGRectMake(0, 0, 0, 0);
int verticalPadding = 10;
for(UIButton *btn in allButtons)
{
if(!btn.hidden)
{
btn.frame = CGRectMake(lastButtonFrame.origin.x, lastButtonFrame.origin.y+lastButtonFrame.size.height+verticalPadding, btn.frame.size.width, btn.frame.size.height);
lastButtonFrame = btn.frame;
}
}
}
-(void)randomizeButtons:(UIButton *)btn
{
// Randomize the visiblity of the buttons and update the interface
for(UIButton *btn in allButtons)
{
btn.hidden = arc4random_uniform(2)-1 > 0;
}
[self updateButtonLayout];
}

nested scrollview in iphone

I am new to iphone development . Can anyone please tell me how to add a vertical scrollview inside a horizontal scroll view. I went through many samples but couldn't get a clear picture about it . I wan my view to be scrolled in both vertical and horizontal directions. Any help is appreciated.
Here is my code for scrolling:
EDIT: Here is my code for scrolling
self.firstScroll.pagingEnabled=YES;
self.firstScroll.clipsToBounds=YES;
int numberOfViews=3;
for(int i=0;i<numberOfViews;i++){
CGFloat xOrigin=self.view.frame.size.width*i;
UIView *awesomeView=[[UIView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
awesomeView.backgroundColor=[UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[self.firstScroll addSubview:awesomeView];
}
self.firstScroll.contentSize=CGSizeMake(self.view.frame.size.width*numberOfViews, self.view.frame.size.height);
[self.view addSubview:firstScroll];
self.nextVerticalScroll.pagingEnabled=YES;
for(int i=0;i<numberOfViews ;i++){
CGFloat yOrigin=self.view.frame.size.height * i;
UIView *verticalView=[[UIView alloc]initWithFrame:CGRectMake(0, yOrigin, self.view.frame.size.width, self.view.frame.size.height)];
verticalView.backgroundColor=[UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[self.nextVerticalScroll addSubview:verticalView];
}
self.nextVerticalScroll.contentSize=CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*numberOfViews);
[self.view addSubview:nextVerticalScroll];
Thanks,
Raj
You probably do not want to have scrollviews within scrollviews because you can't control which gets the horizontal gestures and which gets the vertical gestures (without a lot of hassle, at least). It is much easier to have a single scrollview with a contentSize that is bigger horizontally and vertically than the bounds of the scrollview itself, e.g.:
- (void)configureScrollView
{
NSInteger rows = 4;
NSInteger cols = 5;
CGFloat width = self.scrollView.bounds.size.width;
CGFloat height = self.scrollView.bounds.size.height;
// configure my scroll view itself
self.scrollView.contentSize = CGSizeMake(width * cols, height * rows);
self.scrollView.pagingEnabled = YES;
self.scrollView.backgroundColor = [UIColor darkGrayColor];
// now let's add the labels to the scrollview
for (NSInteger row = 0; row < rows; row++)
{
for (NSInteger col = 0; col < cols; col++)
{
// making my label just a little smaller than the scrollview's bounds so I can easily see the scrolling/paging
CGRect frame = CGRectMake((width * col) + 20.0, (height * row) + 20.0, width - 40.0, height - 40.0);
// create and configure the label
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = [NSString stringWithFormat:#"%1.0f", row * cols + col + 1.0];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];
// add it to my scrollview
[self.scrollView addSubview:label];
}
}
}
I'm just filling my scroll view with 20 different text labels (and colored the background of the scrollview differently from the labels so I could see them), but it demonstrates the basic idea.
Please if you have added Paging in XIB then remove it...I think it will help you.

Move left and right in UIScrollView

I have a UIScrollView which scrolls only horizontally. I have a situation where I have views filled by array in UIScrollView. There are three views which altogether make one single component in UIScrollView (there are many such components). Component contains :
UILabel
UIButton
UIView (for underlying text)
I have placed two arrow keys(left and right) at the ends of UIScrollView. On touching left arrow I am shifting one position left (with complete string to display) in UIScrollView and one position right (with complete string to display) in case of right arrow button.
Till now I am able to perform left arrow action. But I have no idea how to perform right arrow touch and how to display complete string to touching arrow keys if only part of that string is being displayed.
I know it is weird that I have a UIScrollView and still want to add arrow keys to move it. But can't help it. This is client's requirement. The following is how I implemented left arrow action:
-(IBAction) onClickLeftArrow
{
NSLog(#"BUTTON VALUE : %i",iButtonValue);
if(iButtonValue <= [m_BCListArray count]) {
NSArray *arr = [scrollDemo subviews];
for(int j = 0; j < [arr count]; j++) {
UIView *view1 = [arr objectAtIndex:j];
[view1 removeFromSuperview];
}
XX = 5.0;
int tagcount = [m_BCListArray count]-iButtonValue;
NSLog(#"%#",m_BCListArray);
for(int i = iButtonValue; i >= 1; i--)
{
UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(XX, 6, 120, 26)];
blabel.text = [m_BCListArray objectAtIndex:[m_BCListArray count]-i];
blabel.backgroundColor = [UIColor clearColor];
blabel.textColor = [UIColor whiteColor];
blabel.font = [UIFont systemFontOfSize:14];
[scrollDemo addSubview:blabel];
//underline code
CGSize expectedLabelSize = [[m_BCListArray objectAtIndex:[m_BCListArray count]-1] sizeWithFont:blabel.font constrainedToSize:blabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = blabel.frame;
newFrame.size.height = expectedLabelSize.height;
blabel.frame = CGRectMake(blabel.frame.origin.x, blabel.frame.origin.y, expectedLabelSize.width+10, expectedLabelSize.height);
blabel.numberOfLines = 1;
[blabel sizeToFit];
int width=blabel.bounds.size.width;
int height=blabel.bounds.size.height;
UIButton *btnContent = [UIButton buttonWithType:UIButtonTypeCustom];
[btnContent addTarget:self action:#selector(SelectButton:)forControlEvents:UIControlEventTouchDown];
btnContent.tag = tagcount+1;
btnContent.frame=CGRectMake(XX, 2.0, width+10, height);
[scrollDemo addSubview:btnContent];
scrollDemo.contentSize = CGSizeMake(XX+50, 32);
//scrollDemo.contentSize = CGSizeMake(expectedLabelSize.width,expectedLabelSize.height);
UIView *viewUnderline=[[UIView alloc] init];
viewUnderline.frame=CGRectMake(XX, 26, width, 1);
viewUnderline.backgroundColor=[UIColor whiteColor];
[scrollDemo addSubview:viewUnderline];
[viewUnderline release];
scrollDemo.contentSize = CGSizeMake(XX+width+10, 32);
XX = XX + width+10;
iRight = iRight + 1;
tagcount ++;
// iRight --;
}
}
iButtonValue = iButtonValue+1;
}
Set the contentOffset of UIScrollView on the Button click action and u'll get your desired effect.

Horizontal UIScrollView and hundreds of thumbnail images in iOS?

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))