How to disable horizontal scrolling of UIScrollView? - ios

I have a UIView like iPhone's Springboard. I have created it using a UIScrollView and UIButtons. I want to disable horizontal scrolling on said scrollview. I want only vertical scrolling. How do I accomplish this?

You have to set the contentSize property of the UIScrollView. For example, if your UIScrollView is 320 pixels wide (the width of the screen), then you could do this:
CGSize scrollableSize = CGSizeMake(320, myScrollableHeight);
[myScrollView setContentSize:scrollableSize];
The UIScrollView will then only scroll vertically, because it can already display everything horizontally.

UPDATED: (After #EranMarom pointed out on his comment)
You can stop horizontal scrolling or vertical scrolling in the ScrollViewDelegate Method.
Here it is how,
Stops Horizontal Scrolling:
If you want to scroll horizontally, then you need to increase the contentOffset.x. Preventing that stops the scrollview scroll in horizontal direction.
- (void)scrollViewDidScroll:(UIScrollView *)sender {
sender.contentOffset.x = 0.0
}
Stops Vertical Scrolling:
If you want to scroll vertically, then you need to increase the contentOffset.y. Preventing that stops the scrollview scroll in vertical direction.
- (void)scrollViewDidScroll:(UIScrollView *)sender {
sender.contentOffset.y = 0.0
}
Above code prevents the changes in x and y of a scrollview contentOffset and it leads to stop the scrolling in scrollViewDidScroll: method.

since iOS7 use
self.automaticallyAdjustsScrollViewInsets = NO;
//and create you page scroller with 3 pages
self.pageView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.pageView setContentSize:CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height)];
[self.pageView setShowsVerticalScrollIndicator:NO];
[self.pageView setPagingEnabled:YES];
[self.view addSubview:self.pageView];

Swift solution
Create two outlets, one for your view and one for your scroll view:
#IBOutlet weak var myView: UIView!
#IBOutlet weak var scrollView: UIScrollView!
Then in your viewDidLayoutSubviews you can add the following code:
let scrollSize = CGSize(width: myView.frame.size.width,
height: myView.frame.size.height)
scrollView.contentSize = scrollSize
What we've done is collected the height and width of the view and set the scrollViews content size to match it. This will stop your scrollview from scrolling horizontally.
More Thoughts:
CGSizeMake takes a width & height using CGFloats. You may need to use your UIScrollViews existing height for the second parameter. Which would look like this:
let scrollSize = CGSize(width: myView.frame.size.width,
height: scrollView.contentSize.height)

In my case, with Swift 4.2 you can use:
Disable vertical scroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentOffset.y = 0.0
}
Disable horizontal scroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentOffset.x = 0.0
}

In my case the width of the contentView was greater than the width of UIScrollView and that was the reason for unwanted horizontal scrolling. I solved it by setting the width of contentView equal to width of UIScrollView.
Hope it helps someone

You can select the view, then under Attributes Inspector uncheck User Interaction Enabled .

Introduced in iOS 11 is a new property on UIScrollView
var contentLayoutGuide: UILayoutGuide
The documentation states that you:
Use this layout guide when you want to create Auto Layout constraints related to the content area of a scroll view.
Along with any other Autolayout constraints that you might be adding you will want to constrain the widthAnchor of the UIScrollView's contentLayoutGuide to be the same size as the "frame". You can use the frameLayoutGuide (also introduced in iOS 11) or any external width (such as your superView's.)
example:
NSLayoutConstraint.activate([
scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.widthAnchor)
])
Documentation:
https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide

#Gulfam Khan's answer is the correct one, I am adding imagery to help the concept get more visibility.
When we set the contentView to have equal width's with the Scroll view, if the multiplier is even slightly greater than 1:1, then we will get horizontal scrolling.
Here is what it produces:
If you do not want horizontal scrolling, you most likely do not have horizontal content that exceeds the width of the superview.
Therefore if you ensure the contentView width does not exceed the width of the scroll view, that will automatically resolve the problem as UIKit recognizes there is no horizontal content to scroll to. Like so:
Now you should only see vertical:

I had the tableview contentInset set in viewDidLoad (as below) that what causing the horizontal scrolling
self.tableView.contentInset = UIEdgeInsetsMake(0, 30, 0, 0);
Check if there are any tableview contentInset set for different reasons and disable it

I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.
However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.
So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

Try This:
CGSize scrollSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, scrollHeight);
[scrollView setContentSize: scrollSize];

Disable horizontal scrolling by overriding contentOffset property in subclass.
override var contentOffset: CGPoint {
get {
return super.contentOffset
}
set {
super.contentOffset = CGPoint(x: 0, y: newValue.y)
}
}

Once I did it replacing the UIScrollView with a UITableView with only 1 cell, it worked fine.

Use this single line.
self.automaticallyAdjustsScrollViewInsets = NO;

Related

swift: how to adjust table view's height to fit super view's height

I have a viewController into which I dragged a tableView, but when I load data in the tableView I get a scroll, what I want is to extend this tableView to its height to fill its superView. I tried to resize the tableView by setting tableView.frame.height = tableView.contentSize.height in viewDidAppear and it worked but I don't get a scroll in the superView, the tableView just got expanded and the content is down the view but I cant scroll, I tried to put this tableView inside a scrollView but still the same thing, what can I do?
yourTableview.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
Basically what you did was adjust the height of the tableView to be is the height if its content rather than the height of the screen (the content height is larger than the screen)
The table should carry the height of the screen (or any height you want) and if your content is bigger than the frame of your tableView it will automatically have the scrolling enabled.
Hope this helps!
If you want your scrollview to be scrollable, you need to indicate its contentSize by dynamically calculating the height of its nested components:
scrollView.isScrollEnabled = true
scrollView.contentSize = imageView.frame.height + tableview1.frame.height + tableview2.frame.height + netLabel.frame.height
Notice that you may also have to include your margins' height
I just needed to add the constraint of height of my table as an Outlet like this #IBOutlet weak var myConstraint: NSLayoutConstraint!, and the do myConstraint.constant = myTable.contentSize.height in viewDidAppear

How to make UIScrollView zoom in only one direction when using auto layout

I'm attempting to make a UIScrollView only allow zooming in the horizontal direction. The scroll view is setup with a pure autolayout approach. The usual approach is as suggested in a number of Stack Overflow answers (e.g. this one) and other resources. I have successfully used this in apps before autolayout existed. The approach is as follows: in the scroll view's content view, I override setTransform(), and modify the passed in transform to only scale in the x direction:
override var transform: CGAffineTransform {
get { return super.transform }
set {
var t = newValue
t.d = 1.0
super.transform = t
}
}
I also reset the scroll view's content offset so that it doesn't scroll vertically during the zoom:
func scrollViewDidZoom(scrollView: UIScrollView) {
scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.frame.height)
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0.0)
}
This works very nicely when not using autolayout:
However, when using autolayout, the content offset ends up wrong during zooming. While the content view only scales in the horizontal direction, it moves vertically:
I've put an example project on GitHub (used to make the videos in this question). It contains two storyboards, Main.storyboard, and NoAutolayout.storyboard, which are identical except that Main.storyboard has autolayout turned on while NoAutolayout does not. Switch between them by changing the Main Interface project setting and you can see behavior in both cases.
I'd really rather not switch off autolayout as it solves a number of problems with implementing my UI in a much nicer way than is required with manual layout. Is there a way to keep the vertical content offset correct (that is, zero) during zooming with autolayout?
EDIT: I've added a third storyboard, AutolayoutVariableColumns.storyboard, to the sample project. This adds a text field to change the number of columns in the GridView, which changes its intrinsic content size. This more closely shows the behavior I need in the real app that prompted this question.
Think I figured it out. You need to apply a translation in the transform to offset the centering UIScrollView tries to do while zooming.
Add this to your GridView:
var unzoomedViewHeight: CGFloat?
override func layoutSubviews() {
super.layoutSubviews()
unzoomedViewHeight = frame.size.height
}
override var transform: CGAffineTransform {
get { return super.transform }
set {
if let unzoomedViewHeight = unzoomedViewHeight {
var t = newValue
t.d = 1.0
t.ty = (1.0 - t.a) * unzoomedViewHeight/2
super.transform = t
}
}
}
To compute the transform, we need to know the unzoomed height of the view. Here, I'm just grabbing the frame size during layoutSubviews() and assuming it contains the unzoomed height. There are probably some edge cases where that's not correct; might be a better place in the view update cycle to calculate the height, but this is the basic idea.
Try setting translatesAutoresizingMaskIntoConstraints
func scrollViewDidZoom(scrollView: UIScrollView) {
gridView.translatesAutoresizingMaskIntoConstraints = true
}
In the sample project it works. If this is not sufficient, try creating new constraints programmatically in scrollViewDidEndZooming: might help.
Also, if this does not help, please update the sample project so we can reproduce the problem with variable intrinsicContentSize()
This article by Ole Begemann helped me a lot How I Learned to Stop Worrying and Love Cocoa Auto Layout
WWDC 2015 video
Mysteries of Auto Layout, Part 1
Mysteries of Auto Layout, Part 2
And so luckily, there's a flag for that. It's called translatesAutoResizingMask IntoConstraints [without space].
It's a bit of a mouthful, but it pretty much does what it says. It makes views behave the way that they did under the Legacy Layout system but in an Auto Layout world.
Although #Anna's solution works, UIScrollView provides a way of working with Auto Layout. But because scroll views works a little differently from other views, constraints are interpreted differently too:
Constraints between the edges/margins of scroll view and its contents attaches to the scroll view's content area.
Constraints between the height, width, or centers attach to the scroll view’s frame.
Constraints between scroll view and views outside scroll view works like an ordinary view.
So, when you add a subview to the scroll view pinned to its edges/margins, that subview becomes the scroll view's content area or content view.
Apple suggests the following approach in Working with Scroll Views:
Add the scroll view to the scene.
Draw constraints to define the scroll view’s size and position, as normal.
Add a view to the scroll view. Set the view’s Xcode specific label to Content View.
Pin the content view’s top, bottom, leading, and trailing edges to the scroll view’s corresponding edges. The content view now defines
the scroll view’s content area.
(...)
(...)
Lay out the scroll view’s content inside the content view. Use constraints to position the content inside the content view as normal.
In your case, the GridView must be inside the content view:
You can keep the grid view constraints that you have been using but, now, attached to content view. And for the horizontal-only zooming, keep the code exactly as it is. Your transform overriding handle it very well.
I'm not sure if this satisfies your requirement of 100% autolayout, but here's one solution, where the UIScrollView is set with autolayout and gridView added as a subview to it.
Your ViewController.swift should look like this:
// Add an outlet for the scrollView in interface builder.
#IBOutlet weak var scrollView: UIScrollView!
// Remove the outlet and view for gridView.
//#IBOutlet var gridView: GridView!
// Create the gridView here:
var gridView: GridView!
// Setup some views
override func viewDidLoad() {
super.viewDidLoad()
// The width for the gridView is set to 1000 here, change if needed.
gridView = GridView(frame: CGRect(x: 0, y: 0, width: 1000, height: self.view.bounds.height))
scrollView.addSubview(gridView)
scrollView.contentSize = CGSize(width: gridView.frame.width, height: scrollView.frame.height)
gridView.contentMode = .ScaleAspectFill
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return gridView
}
func scrollViewDidZoom(scrollView: UIScrollView) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0.0)
scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.frame.height)
}

Scroll View ios 8 Xcode not Scrolling - Swift

I am very new to Swift and developing on ios but I cannot find a way to make the UIScrollView to scroll down and stay down. I have been trying tons of tutorials over this and still nothing. I have a ContentView element inside of my ScrollView element. This ContentView has all of my boxes that I want it to scroll through but it does not scroll. It does though bounce if that makes any difference...can anyone send me in the right direction?
Try setting the contentSize in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = CGSize(width: 375, height: 1500)
}
I finally figured it out after 2 days and it was very simple. All I did was set the scrollView to the size of the screen but then set the content view height at 1500px and it started working. Thanks everyone!
Sounds like uou may not have set the contentSize for your scroll view. To do that if you're not using Auto layout:
scrollView.contentSize = // The size of your content.
If you are using Auto layout you need to make sure you have NSLayoutConstraints from each edge of your content to each corresponding edge of your UIScrollView. By doing this the content size of your UIScrollView will be set automatically.
Hope that helps.
Just wanted to add a note to FreeTheStudentsAnswer in case anyone had a similar issue to me - I set the scrollView to the size of the screen and then set the content view height at a larger value and it started working only when I set these in the viewDidAppear instead of viewDidLoad. Not sure if that will help anyone, but that fixed my issue
In scrollview, scroll happens only if the scrollview has enough space to scroll its content.
You said the scrollview and its content view have the same dimensions.
Then it won't scroll.
Scrollview.contentSize should be at least double the size of scrollview if you want it to scroll.
Hint: scrollview dimension should not be greater than the iPhone screen size. And scrollview content size should be greater than the scrollview.
Scroll view scrolls through its contentview.
SWIFT 4.0 Update
#IBOutlet weak var myScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
myScrollView.alwaysBounceVertical = true
myScrollView.alwaysBounceHorizontal = true
myScrollView.isScrollEnabled = true
myScrollView.contentSize = CGSize(width: 375, height: 1000)
}
Try This
1.scrollView.bounds = YES;
2.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: YourContentView.frame.size.height);

Disabling vertical scrolling in UIScrollView in swift?

So I have my UIScrollView,
var myScrollView = UIScrollView(frame:theFrame)
and I would like to disable vertical scrolling. Does anyone know how to implement this using Swift?
Another way to do this is to set the height to 1.0
scrollView.contentSize = CGSizeMake(theFrame.size.height, 1.0)
Try this. This sets the content size to the height of the frame so it disables vertical scrolling because it can display the whole size.
let scrollSize = CGSizeMake(theFrame.size.height, yourWidth)
myScrollView.contentSize = scrollSize

UIScrollView not scrolling in iOS7 with autolayout on

I have a UIScrollView with a 6 textfields in it and a button inside of it. There is not enough content in the scrollView to make it scroll.
But when the keyboard shows, I would like the scrollview to scroll so the user doesn't have to dismiss the keyboard in order to select another textfield that is hidden by the keyboard.
I am using iOS7 and have autolayout enabled.
Any suggestions?
I am using storyboards and the only code I have is the following.
reg.h file
interface registerViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>
In order to make a scrollview scrollable, the content size must be larger than the scrollview's frame so the scrollview has something to scroll to. Use setContentSize to adjust the content size:
[scrollview setContentSize:CGSizeMake(width, height)];
In this case, you should adjust the size to view.frame.width, view.frame.height + keyboard_height, then adjust the content offset once the keyboard appears:
[scrollview setContentOffset:CGPointMake(0, 0 - keyboard_height)];
If for some screwy, autolayout-related reason this still doesn't make the view scrollable, implement this setContentSize function in viewDidLayoutSubviews in order to override the autolayout:
- (void)viewDidLayoutSubviews {
[scrollview setContentSize:CGSizeMake(width, height)];
}
EDIT: To reset the scrollview after dismissing the keyboard, reset the scrollview content size to the scrollview's frame and the offset to zero:
[scrollview setContentSize:CGSizeMake(scrollview.frame.size.width, scrollview.frame.size.height)];
[scrollview setContentOffset:CGPointZero];
P.S. To animate the content offset, use:
[scrollview setContentOffset:offsetSize animated:YES];
There is a contentInset property of UIScrollViews, you can set the contentInset to make additional space at the bottom to allow for scrolling without changing contentSize.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, 100, 0.0);
scrollView.contentInset = contentInsets;
above code adds 100 points inset at the bottom.
By the way, there is an official document about this matter. It explains everything you should do. You can find it here. You can find what you are looking for under the section 'Moving Content That Is Located Under the Keyboard'
Try
Create Scroll view
Add View to the scroll view (In my case i added view as mainView).
Set ScrollView autoresizing.
Set MainView autoresizing.
To set the Scroll content Size equal to the view created add below line
Add the below line
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
self.scrollView.contentSize = self.mainView.frame.size;
}

Resources