Adding multiple items to UIScrollView, but can't scroll? - ios

I'm writing a UI for iOS and I need to create a scrolling view of note-type widgets. I'm experimenting with creating a scrollview and adding some UIView objects to it, but for some reason, I can't scroll, am I doing something wrong? Here's what I'm doing:
[_testScrollView setBackgroundColor:[UIColor purpleColor]];
NSUInteger size = 100;
float height = _testScrollView.frame.size.height/10;
float width = _testScrollView.frame.size.width;
float currTop = 0;
CGSize fooSize = CGSizeMake(_testScrollView.frame.size.width, _testScrollView.frame.size.height);
[_testScrollView setContentSize:fooSize];
for (NSUInteger i = 0; i < size; i++)
{
double red = ((double)arc4random() / ARC4RANDOM_MAX);
double green = ((double)arc4random() / ARC4RANDOM_MAX);
double blue = ((double)arc4random() / ARC4RANDOM_MAX);
CGRect currFrame = CGRectMake(0, currTop, width, height);
UIView* testView = [[UIView alloc] initWithFrame:currFrame];
[testView setBackgroundColor:[UIColor colorWithRed:red green:green blue:blue alpha:1.0]];
[_testScrollView addSubview:testView];
currTop += height;
}
I would've expected to scroll through the scrollview and be able to go through all of the 100 UIViews added. What am I missing?

you need to set the content size for your scroll view to the height of all the uiviews. use
setContentSize:cgSizeMake(_testScrollView.frame.size.width,size*height)
after the for loop

Just print(Log screen) your height of contentsize in scrollview.there you can see the scrollview height...you need to add heights of all subviews to get height of contentsize for scrollview...

Related

How to programmatically sizeToFit width AND height on UILabel?

I'm programmatically creating multi-line UILabels ([label setNumberOfLines:0];).
The built-in sizeToFit method of UILabel works great for 1 line UILabels, but for multi-line text, it sets the height properly, but the width is set too small, causing longer text lines to wrap.
I don't know the label width until after the user enters their text. I want to resize the labels to fit the width of the longest line of text. And per #DonMag's comment, I also want to restrict the label to not be wider than the screen.
I tried different lineBreakMode settings but there isn't a 'nowrap' option.
I've searched SO and there are many related solutions but none that solve the problem of sizeToFit for both width and height.
Is there a way to programmatically size a multi-line UILabel to fit BOTH the width AND the height of the text?
You can do this with boundingRectWithSize...
Add your label to the view and give it a starting width constraint (doesn't really matter what value, as it will be changed).
Keep a reference to that width constraint (IBOutlet works fine if you're using IB).
Don't give it a height constraint.
When you set the text of the label, you can use this to change its width:
// get the font of the label
UIFont *theFont = _theLabel.font;
// get the text of the label
NSString *theString = _theLabel.text;
// calculate the bounding rect, limiting the width to the width of the view
CGRect r = [theString boundingRectWithSize:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: theFont}
context:nil];
// change the constant of the constraint to the calculated width
_theWidthConstraint.constant = ceil(r.size.width);
// NOTE: If you are *not* using auto-layout,
// this same calculation can be used to explicitly set
// the .frame of the label.
Edit:
As per the OP's requirement, a complete, runnable example -- using code only, no storyboards / IB -- can be found here: https://github.com/DonMag/MultilineLabelFitWidth
Edit 2:
GitHub project updated... now includes examples for both manual frame setting and auto layout / constraints.
With some more experimentation, I found something that does the trick that I have not seen in SO (yet...). In general it works like this:
Find the longest text line
Set numberOfLines to 1 (temporarily)
Set label text to longest text line
Call label.sizeToFit (sets label width for longest line)
Set numberOfLines to 0 (multi-line)
Set label text to full multi-line text
Call label.sizeToFit (sets label height for all lines)
Voila! Now your UILabel is sized to fit your multi-line text.
Here is an example (demo project on GitHub: UILabelSizeToFitDemo):
- (UILabel *)label = nil;
- (void)updateLabel:(NSString *)notes {
// close to the "sticky" notes color
UIColor *bananaColor = [ViewController colorWithHexString:#"#FFFC79"];
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.numberOfLines = 0;
_label.textColor = UIColor.blackColor;
[_label setBackgroundColor:[bananaColor colorWithAlphaComponent:0.9f]];
_label.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_label];
}
// make font size based on screen size
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat fontSize = MIN(screenWidth,screenHeight) / 12;
[_label setFont:[UIFont systemFontOfSize:fontSize]];
// split lines
NSArray *lines = [notes componentsSeparatedByString:#"\n"];
NSString *longestLine = lines[0]; // prime it with 1st line
// fill a temp UILabel with each line to find the longest line
for (int i = 0; i < lines.count; i++) {
NSString *line = (NSString *)lines[i];
if (longestLine == nil || line.length > longestLine.length) {
longestLine = line;
}
}
// force UILabel to fit the largest line
[_label setNumberOfLines:1];
[_label setText:longestLine];
[_label sizeToFit];
// make sure it doesn't go off the screen
if (_label.frame.size.width > screenWidth) {
CGRect frame = _label.frame;
frame.size.width = screenWidth - 20;
_label.frame = frame;
}
// now fill with the actual notes (this saves the previous width)
[_label setNumberOfLines:0];
[_label setText:notes];
[_label sizeToFit];
// center the label in my view
CGPoint center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
[_label setCenter:center];
}
UPDATE: Here is an alternate complete solution, using the boundinRectWithSize from the code snippet by #DonMag:
-(void)updateLabel:(NSString *)notes {
// close to the "sticky" notes color
UIColor *bananaColor = [ViewController colorWithHexString:#"#FFFC79"];
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.numberOfLines = 0;
_label.textColor = UIColor.blackColor;
_label.backgroundColor = [bananaColor colorWithAlphaComponent:0.9f];
_label.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_label];
}
// set new text
_label.text = notes;
// make font size based on screen size
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat fontSize = MIN(screenWidth,screenHeight) / 12;
[_label setFont:[UIFont systemFontOfSize:fontSize]];
// calculate the bounding rect, limiting the width to the width of the view
CGRect frame = [notes boundingRectWithSize:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: _label.font}
context:nil];
// set frame and then use sizeToFit
[_label setFrame:frame];
[_label sizeToFit];
// center the label in my view
CGPoint center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
[_label setCenter:center];
}

iOS8 UIView width 320

There is the question: I set a custom view named ZHLockView. I put it in the storyboard and I set the constraints. But I can't get the correct width in - (id)initWithCoder:(NSCoder *)aDecoder, it is always 320, what should I do to get the correct width?
Last I know in the - (void)layoutSubviews, I can get the right width, but it will going twice. Is there a better idea?
See, you're getting width 320 because your view is of that size on storyboard.
If the width of the view is equal to superview, which is indeed again equal to width of device, you can use following code to get width of view at anytime and dont need to worry about where to write.
Swift :-
CGFloat width = CGRectGetWidth(UIScreen.mainScreen.bounds);
CGFloat height = CGRectGetHeight(UIScreen.mainScreen.bounds);
Objective-C :-
CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
CGFloat height = CGRectGetHeight([[UIScreen mainScreen] bounds]);
Hope you understood and it helps you.. :)
the code is here
objc
#define KScreenWidth [UIScreen mainScreen].bounds.size.width
CGFloat height = 0;
CGFloat margin = (KScreenWidth - columnCount * btnW) / (columnCount + 1);
for (int i = 0; i < btnCount; i++) {
int row = i / columnCount;
int column = i % columnCount;
CGFloat btnX = margin + column * (btnW + margin);
CGFloat btnY = row * (btnW + margin);
height = btnH + btnY;
ZHButtonView *button = [[ZHButtonView alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
button.userInteractionEnabled = NO;
button.currentIndex = i;
[button setBackgroundImage:[UIImage imageNamed:#"gesture_node_normal"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"gesture_node_highlighted"] forState:UIControlStateSelected];
[self addSubview:button];
}
The view will be load with the value in the xib at the first start, next when the autolayout engine makes the first pass, it will be set to a new value according to the constraints set.
Why would you need to know the size? Autolayout is made to do not care about it.
-layoutSubviews, -viewWillLayout, -viewDidLayout are called when the layout engine needs a update, that could means Different times before displaying your view.

UIScrollview doesn't scroll iOS

I'm creating several scroll views in one view that scroll horizontally. The following code works fine:
-(void)updateSection {
builder = [NSMutableArray array];
float xPosition = 0;
float xposbut = 100;
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, self.frame.size.width, self.frame.size.height - 69)];
scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
scrollView.delegate = self;
[self addSubview:scrollView];
for (int i = 1; i < itemArticleArray.count; i++) {
ItemView *item = [ItemView loadNibs];
item.frame = CGRectMake(xposbut, 10, item.frame.size.width, item.frame.size.height);
xPosition += scrollView.frame.size.width + 2;
xposbut += 500;
UIView *seperatorView = [[UIView alloc] initWithFrame:CGRectMake(xposbut - 50, 4, 2, scrollView.frame.size.height - 8)];
[scrollView addSubview:seperatorView];
xPosition += scrollView.frame.size.width + 4;
[scrollView addSubview: item];
[builder addObject:item];
}
[scrollView setContentSize:CGSizeMake(xposbut, scrollView.frame.size.height)];
[self addSubview:scrollView];
}
However, when I change the 8th line of code to the following:
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 400, self.frame.size.width, self.frame.size.height - 69)];
It cause the layout to look fine, but the scroll views do then not scroll at all. Any ideas?
you set the contentSize.height to the scrollView.frame.size.height and so the scrollView cant scroll. you have to set the contentSize to the total height of you scrollView, including the not visible area. The frame is only the area on screen.
UIScrollview will scroll when content size is bigger then frame size. In your code you set content size equal to frame size that's why your scrollview is not scrolling.
Set the content size for the scroll view. The content size should be greater than frame.size, then only the scroll view will scroll. And also enable scrolling.
Use the code
scrollView.scrollEnabled=YES;
scrollView.contentSize=CGSizeMake(CGFloat width, CGFloat height);
Height should be greater than scrollView.frame.size.height and add contents inside scrollview beyond the scrolview's frame.
You must give the scroll some space to work so check this out:
Create the scroll in the storyboard
Create an outlet for the scroll
And the in the .m file you must paste these lines
The code:
(void)viewDidLoad {
[super viewDidLoad];
yourScroll.scrollEnabled=YES;
yourScroll.contentSize=CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*2);
}
/*
* yourScroll.contentSize=CGSizeMake(your desired scroll width, your desired scroll height);
* The values must be bigger than the viewController size
*/

How do I use UIPageControl in my app?

I am making an app where I need some images can be scrolled through using a UIPageControl. Sadly, I don't know how to use a UIPageControl, or a UIScrollView either. A link to a YouTube video or Xcode documentation by Apple would be much appreciated!
Thanks in advance!!
here is a code which will help you
CGSize size = [[UIScreen mainScreen] bounds].size;
CGFloat frameX = size.width;
CGFloat frameY = size.height-30; //padding for UIpageControl
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(offsetX, offsetY, frameX, frameY)];
scrollView.pagingEnabled = YES;
scrollView.backgroundColor = [UIColor clearColor];
scrollView.contentSize = CGSizeMake(frameX, frameY);
[self.view addSubview: scrollView];
// let say you have array of image in imageArray
for(int i = 0; i < [imageArray]; i++)
{
UIImage *image = [UIImage imageNamed:[imageArray objectAtIndex:i]];
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(frameX * i, 0.0, frameX, frameY);
[scrollView addSubview:imageView];
}
scrollView.contentSize = CGSizeMake(frameX*[imageArray count], frameY);
please declare the variables according to scope of use. i have declared all the variables locally so that might not get confuse and also add the UIPageControl at the bottom of your viewcontroller
Implement the delegate method of UIScrollView to the current Page indicator
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
float width = scrollView.frame.size.width;
float xPos = scrollView.contentOffset.x+10;
//Calculate the page we are on based on x coordinate position and width of scroll view
pageControl.currentPage = (int)xPos/width;
}
where pageControl is UIPageControl added on bottom your viewcontroller
ScrollView:
ScrollView is used to display the more number views/Objects. We can display those views by horizontal or vertical scrolling.
You can handle zooming, panning, scrolling etc.
You can go through some of these tutorials
Are there any good UIScrollView Tutorials on the net?
https://developer.apple.com/library/ios/documentation/windowsviews/conceptual/UIScrollView_pg/CreatingBasicScrollViews/CreatingBasicScrollViews.html
Example Code for Scrollview:
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height)];
//This will create a scrollview of device screen frame
You can enable the scrolling by
scroll.scrollEnabled = YES;
Example for adding 3 views to scrollview
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
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];
[scroll addSubview:awesomeView];
[awesomeView release];
}
// 3 views added horizontally to the scrollview by using xOrigin.
The most important part in this for is to understand the xOrigin. This will place every UIView exactly where the previous UIView has stopped, in other words, each UIView will start at the end of the previous one.
Now we got the scrollview with 3 views added horrizontally.
Set the UIScrollView contentSize
scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
The contentSize is just the sum of the widths of the three UIViews, if the width of each UIView is 320, and we have three UIViews, your contentSize width will be 920.
[self.view addSubview:scroll];
[scroll release];
//Add scrollview to viewcontroller
Page Control:
A Page control presents the user with a set of horizontal dots representing pages. The current page is presented as a white dot. The user can go from the current page to the next or to the previous page.
To enable paging you need to add
scroll.pagingEnabled = YES;
pageControl = [[UIPageControl alloc] init]; //SET a property of UIPageControl
pageControl.frame = CGRectMake(100,self.view.frame.size.height-100,self.view.frame.size.width-200,100);
pageControl.numberOfPages = 3; //as we added 3 diff views
pageControl.currentPage = 0;
Add delegate method of scrollview to implement the pagecontrol dots while scrolling
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x – pageWidth / 2 ) / pageWidth) + 1; //this provide you the page number
pageControl.currentPage = page;// this displays the white dot as current page
}
Now you can see pagecontrol for scrollview. Hope you understand. Refer this too
https://developer.apple.com/library/ios/documentation/uikit/reference/UIPageControl_Class/Reference/Reference.html
This is a very good tutorial by the Ray Wenderlich team on how to set up a paging scrollview: How To Use UIScrollView to Scroll and Zoom Content
Apple's documentation also has an example of how to implement a paging scroll view: PhotoScroller
My answer to this previous question may also be useful to you.

UIScrollView Direction RTL for Right to Left Languages

Can we change the behavior of UIScrollView that it scrolls RTL content in it's reverse mode.
You can achieve it by rotating UIScrollView in Child views by 180 (Pi).
self.scrollView.transform = CGAffineTransformMakeRotation(M_PI);
subView.transform = CGAffineTransformMakeRotation(M_PI);
count = 6;
[self.scrollView setFrame:CGRectMake(scrollView.frame.origin.x, scrollView.frame.origin.y, 320, 480)];
[pageControl setNumberOfPages:count];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * count, self.scrollView.frame.size.height);
for(int i=count-1; i>=0; i--) { //start adding content in reverse mode
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * (count - i - 1); //ar
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
[imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%i.png", i]]];
[self.scrollView addSubview:imageView];
}
//scroll to the last frame as it's the first page for RTL languages
CGRect frame;
frame.origin.x = scrollView.frame.size.width * (count - 1);
frame.origin.y = 0;
frame.size = scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:NO];
The page control also needs to be indicate the last dot as the first dot (or first page)
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = (page % count);
}
I try it for xCode 7 and iOS 9 work good.
[self._imagesScrollView setTransform:CGAffineTransformMakeScale(-1, 1)];
I m not sure if I understand the question correctly but I take it like this: You want to have a (let's say) horizontal UIScrollView where you can add elements from right to left and when the contents exceed the scroll view frame you want to be able to scroll to the left rather than to the right in order to see the last elements.
In this case you can do this. For every new element calculate the total width you need and set it as contentOffset:
[scrollView setContentSize:CGSizeMake(self.childView.frame.size.width,
scrollView.frame.size.height)];
Above I have a childView where the elements are added. It is placed at the right most position inside the scrollView minus 1 element width. Every time an element is added call:
[scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x + kElementWidth,0.0)];
which will offset everything to the left. Then:
self.videoQueueCollectionView.center = CGPointMake(self.childView.center.x + kElementWidth,
self.childView.center.y);
That will snap eveything back to where it was BUT with the contentOffset set to the left. Which means that you can now scroll to the right.
I use this code for Swift 3
self.scrollView.transform = CGAffineTransform(scaleX:-1,y: 1);
You can achieve this by setting semanticContentAttribute
self.scrollView.semanticContentAttribute = .forceRightToLeft

Resources