Adding a view causes constraints in Storyboard to update - ios

I created a UIScrollView with its constraints set in storyboard, but I sometimes move the UIScrollView to a different position at runtime.
My problem happens when I create a custom UIView programmatically and add it the the main UIView. My constraints will update, and if my UIScrollView is not is the same location, it will be moved to the storyboard setting.
For instance, imagining my UIScrollView is pinned to the top of the screen, and then I move it to the bottom of the screen at runtime. If I execute this code:
let menu = UIView()
menu.frame.size = CGSize(width: 210, height: 80)
menu.center = view.center
view.addSubview(menu)
My UIScrollView will moved back to the tap on the screen. I try this but it did not work:
myScrollView.constraints.first?.isActive = false

When using auto-layout and constraints, you cannot change frames by setting the view.frame explicitly.
If you try to do so, then on the next UI update auto-layout will reset the view to its constraints.
If you need to move / size a view at run-time, you'll want to have a reference to the constraint(s) you've set, and then modify the constraint.
For example, if your scroll view is constrained 20-pts from the top of the view, and you want to move it down 50-pts at run-time...
create an IBOutlet for the top constraint
in code, use myTopConstraint.constant = 70.0

Related

Updating AutoLayout Constraints When UIView Height Changes

I currently have a UIView (we'll call this viewB) added to a parent UIScrollView, which we'll call scrollView. This functions as expected, with viewB being added like so;
viewB.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
viewB.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
viewB.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
viewB is taller than scrollView, hence its ability to scroll vertically.
At some point in my app, the user may tap a button, which adds more content to viewB, hence changing viewB's height. On that button tap, scrollView does not seem to know to update any of its constraints, and viewB ends up changing positions and does not appear as expected.
What methods would I call (and on which views) to force AutoLayout to tell scrollView that viewB has changed sizes? Or would it be more efficient to remove viewB from scrollView and then re-add with new constraints?
Subviews inside a view that's inside a scrollview should be hooked properly from top to bottom at any time , so when you add a new subview to viewB you need to insert it properly inside that chain then call
self.view.layoutIfNeeded()
if for e.x you add it at the bottom then you should remove most bottom subview's bottom constraint with viewB and hook it to the top of the new view and re-hook that new's subview's bottom to viewB's bottom plus giving height & width & x constraint finally refresh the layout again which is a tedious problem so you either go with it or with this Tip
Tip : instead of managing constraints manually with UIScrollView you can use a UITableView or replace viewB with a UIStackView that has easily remove/add/insert functions

Add a ScrollView to existing View

I'm developing a little app in Swift 2.0. I have a View with the following hierarchy:
Now, the elements placed in this view can't be displayed entirely in it, so I would like to use a ScrollView in order to be able to scroll all the content.
How I can embed all the content of my Viewto a new ScrollView? Can I do this programmatically by code?
UPDATE: There's an easier way to do this which I didn't know when I posted this answer
1) Go to the viewcontroller on the storyboard and click on something in it and press Command + A. This will select all the elements in the view.
2) Go to Editor -> Embed In -> Scroll View. This will embed all the labels, views, etc into a scrollView.
3) Select the scrollview that you just embedded. Press Control and drag it to the respective class file of the viewcontroller and create an outlet scrollView.
4) Add this to your viewDidLoad()
scrollView.contentSize = CGSizeMake(self.view.frame.width, self.view.frame.height+100)
Make sure the height for the contentSize is more than the size of your view.
ADDING SCROLLVIEW MANUALLY
1) Drag and drop a scrollview from the Object Library onto your viewcontroller in the storyboard and create an outlet to your program as 'scrollView'.
2) Click on your viewcontroller and go to the size inspector and note down the width and height.
3) Click on your scrollview and set the width and height the same as the viewcontroller. and set the X and Y values to 0
4) Click on the scrollView and drag it a little bit to the side
5) Press Command+A to select all the elements including scrollView. Press Command and click on the scrollView to deselect the ScrollView
6)You will have all the elements except the scrollView selected now. Now click and drag them into the scrollView.
7) Now click on the scrollView and set the X and Y values to 0 from the Size Inspector.
8) Add this to your viewDidLoad()
scrollView.contentSize = CGSizeMake(self.view.frame.width, self.view.frame.height+100)
Make sure the height for the contentSize is more than the size of your view.
That should create a scrollView for your view. Some of the elements might be in a slightly different position. You can easily fix them by moving them on your storyBoard.
It can be done even simpeler than ebby94's answer.
1) Go to the viewcontroller on the storyboard and click on something in it and press Command + A. This will select all the elements in the view.
2) Go to Editor -> Embed In -> Scroll View. This will embed all the labels, views, etc into a scrollView.
3) Set the constraints of the Scroll View to the View's edges.
And you're good to go! No need for an outlet.
If you are using Snapkit or creating programmatically.
class ScrollViewController: UIViewController {
lazy var contentViewSize = CGSize(width: self.view.frame.width, height: self.view.frame.height + 320) //Step One
lazy var scrollView : UIScrollView = {
let view = UIScrollView(frame : .zero)
view.frame = self.view.bounds
view.contentInsetAdjustmentBehavior = .never
view.contentSize = contentViewSize
view.backgroundColor = .white
return view
}()
lazy var containerView : UIView = {
let view = UIView()
view.frame.size = contentViewSize
view.backgroundColor = .white
return view
}()
override func viewDidLoad() {
self.view.addSubview(scrollView)
self.scrollView.addSubview(containerView)
//Now Set Add your Constraints in the container View.
}
}
Above accepted answer explanation is enough to achieve the scroll view but I would prefer to create my complete application programatically and I don't use storyboards in my project. This code is for the folks who don't prefer to use storyboards.
Explanation
Step One: Determine your content Size. Here I am taking Exact width and adding 320 more to the height of the screen.
Step Two: Create a scroll view and add desire behaviour of the scroll view. Now, the contentSize of the scroll view should be same as the contentSize you've created above at step one.
By Following Step one and Step Two. You Will be able to set a scroll view on the top of the view. But If you want to add a stretching behaviour then You should follow Step Three
Step Three: Create a container view of the same size of the contentView which you've calculated in step one and set it to the frame of the containerView. By doing this you'll be able to achieve stretching header and footer behaviour in your screen.
Please read make sure to add constraints in the same order as it is set.
Answer Edits are welcome.
I had the same issue. I needed to add scrollview to the existing view.But my main container view has a lots of view inside it. And they were connected to each other. So i was afraid. Finally i did it. the process given below.
Duplicate your View (root View). For this first select the root view then press Command + D
Now delete all the child view view inside the root view
Now add a scroll view to the root view and set constraint to 0,0,0,0
Now add the duplicate(That you duplicated) view to the scroll view and set constraints to 0,0,0,,0 also set the height that you want.
Set width of the duplicate view by equal width with the root view.
Now select the viewController, go the size inspector, select free form size. Then set the height that you entered with duplicate view.
You have almost done. Now you have to connect the child view with outlet or action that you gave in the viewController class.
Thats all.
Selecting all elements and embedding scroll view (editor->embed in->scrollView) works fine.
Adding constraint is much more easy by selecting the constraint warning (Add Missing Constraints).
It's simple. Command A and Command X to specific view controller in StoryBoard. After that take scroll view. On scroll view, just take one view with view controller view height and width equal to scroll View width. Again do Command V and rearrange the constraints. Your problem will be solved.

what should be the height of uiscrollview and main view that i can set after adding other views to uiscrollview

After so much trouble i am able to scroll the scrollview, and it is working fine. Now my question is how to set the dynamic height of scrollview and main view after adding view inside scroll view. As adding height from IB make it static and inside content height may very.
steps that i followed are.
Added a uiview controller inside my storyboard.
Then inside this uiview added one uiscrollview.
Set the height of the main view to 1000 and scrollview to 1000.
Selected the uiscrollview and reset it to suggested constraint.
In this uiscrollview i added many labels, uiviews, textviews, etc programatically.
Now the main isuue is this 1000 height that i set in step 3 is static and the content is dynamic, so how to set height dynamically. and also is it necessary to follow step 4, when i am doing it programatically.
If you know the new subview's height, you can change the frame size by
// Add your subview to scroll view
...
// Set new height
CGRect newScrollFrame;
newScrollFrame.origin = MyScrollView.frame.origin;
newScrollFrame.size = CGSizeMake(MyScrollView.frame.size.width, MyScrollView.frame.size.height + MyNewSubView.frame.size.height);
MyScrollView.frame = newScrollFrame;

How to make uiscrollview only vertical scrolling for ios?

I'm trying to make layout inside scrollview using this one tutorial link
And get the following result link
It will be appreciated for any advices or tutorial links. It needs only vertical scrolling
I am sure there must be other ways to do this but a quick fix is :
1.) Create a width constraint on ContentView in Storyborad.
2.) IBOutlet that widthContraint and set its value to the view frame width in viewDidLoad.
Suppose the name of the constraint outlet is contentViewWidthContraint.
contentViewWidthContraint.constant = self.view.bounds.size.width;
Another alternative to do so from Storyboard, is to fix the Contentview width to the view's width from the storyboard or to the Scrollview, if Scrollview already has a Equal width contraint with superview . Add the "Equal Width" contraint from Contentview to either self.view or to Scrollview (if scrollview, already has the width contraint)
Have you set up the "ContentView" width to match with the scroll view width? I had the same problem and I fixed with "Equal Widths".
"Equal Widths" will tell to your "ContentView" to use the same width of the "Scroll View", which should be fitting the screen if you have set up the constrain properly.
You can do this easily on the storyboard.
Drag and drop, with right click (important!!!), from "ContentView" to "ScrollView"
Release the click, you will be prompted with a menu, select "Equal Widths".
This should fix your problem using the scrollview with AutoLayout from Storyboard editor.
You can find a full tutorial how to use ScrollView with Autolayout and Storyboard here.
I hope this is useful for you :)
In the Storyboard set the width of the elements contained in your UIScrollView equal to the width of this UIScrollView (by selecting all elements and the UIScrollView holding in the panel on the left of your Storyboard and then setting the 'Equal Widths' constraint under 'Pin' on the bottom of your Storyboard). Just pinning the right sides of the elements to that of the UIScrollView won't work as it will adjust the size of its "display view" to the width of the largest element and if this is smaller than the width of the UIScrollView all elements will just appear aligned to its left side.
There is also another possibility that offers a very good result.
You can mark a checkbox:
O programmatically:
scrollView.alwaysBounceVertical = true
Try to set it's width to 0 & height equal to content size like this:
self.scrollView.contentSize = CGSizeMake(0, self.scrollView.contentSize.height);
This will work as you want. Try it & tell if still facing any issue.
For disabling the horizontal scroll, you can set the content size in the -(void)scrollViewDidScroll method.
[self.scrollView setContentOffset: CGPointMake(0, self.scrollView.contentOffset.y)];
self.scrollView.directionalLockEnabled = YES;
This is because scroll view have no idea where your content should end.
But when at least one item inside your scroll view has its "trailing space" constraint attached to a view outside the scroll view (usually a view the scroll view is sitting in or some other view of a higher level, which "knows" its width) - the scroll view will automatically get an idea about your wanted width and won't scroll horizontally (unless that trailing constraint implies having your content outside the screen).
Better if all items inside scroll view have their "trailing space" constraints connected either to each other or to a view outside the scroll view. But not the scroll view itself.
No additional code or extra constraints needed for this to work.
Too set UIScrollView constraints as like below code so it will occupied whole screen.Not exceed the screen size.
Leading Space = 0 from mainView
Top Space = 0 from mainView
Bottom Space = 0 from mainView
Trailing Space = 0 from mainView
You need to set the width of UIScrollView equal to or less than the width of your Parent View. Two ways to do it:
1) You can do this in Storyboard via layout constraints
2) You can do this programatically:
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.scrollView.contentSize.height);

UIScrollView not scrolling

I have a UIScrollView which contains many UIImageViews, UILabels, etc... the labels are much longer that the UIScrollView, but when I run the app, I cannot click and scroll down...
Why might this be?
Thanks
It's always good to show a complete working code snippet:
// in viewDidLoad (if using Autolayout check note below):
UIScrollView *myScrollView;
UIView *contentView;
// scrollview won't scroll unless content size explicitly set
[myScrollView addSubview:contentView];//if the contentView is not already inside your scrollview in your xib/StoryBoard doc
myScrollView.contentSize = contentView.frame.size; //sets ScrollView content size
Swift 4.0
let myScrollView
let contentView
// scrollview won't scroll unless content size explicitly set
myScrollView.addSubview(contentView)//if the contentView is not already inside your scrollview in your xib/StoryBoard doc
myScrollView.contentSize = contentView.frame.size //sets ScrollView content size
I have not found a way to set contentSize in IB (as of Xcode 5.0).
Note:
If you are using Autolayout the best place to put this code is inside the -(void)viewDidLayoutSubviews method .
If you cannot scroll the view even after you set contentSize correctly,
make sure you uncheck "Use AutoLayout" in Interface Builder -> File Inspector.
You need to set the contentSize property of the scroll view in order for it to scroll properly.
If you're using autolayout, you need to set contentSize in viewDidLayoutSubviews in order for it to be applied after the autolayout completes.
The code could look like this:
-(void)viewDidLayoutSubviews
{
// The scrollview needs to know the content size for it to work correctly
self.scrollView.contentSize = CGSizeMake(
self.scrollContent.frame.size.width,
self.scrollContent.frame.size.height + 300
);
}
The answer above is correct - to make scrolling happen, it's necessary to set the content size.
If you're using interface builder a neat way to do this is with user defined runtime attributes. Eg:
Try to resize the content size to huge numbers. I couldn't understand why my scroll view doesn't scroll even when its content size seems to be bigger than control size. I discovered that if the content size is smaller than needed, it doesn't work also.
self.scrollView.contentSize = CGSizeMake(2000, 2000);
Instead of 2000 you can put your own big numbers. And if it works, it means that your content size is not big enough when you resize.
The delegate is not necessary for scroll view to work.
Make sure you have the contentSize property of the scroll view set to the correct size (ie, one large enough to encompass all your content.)
Uncheck 'Use Autolayout' did the trick for me.
Environment:
xCode 5.0.2
Storyboards
ios7
In my case I had to set delaysContentTouches to true because the objects inside the scrollView were all capturing the touch events and handling themselves rather than letting the scrollView itself handle it.
Set contentSize property of UIScrollview in ViewDidLayoutSubviews method. Something like this
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = CGSizeMake(view.frame.size.width, view.frame.size.height)
}
if you are getting a message (IOS8 / swift) that viewDidLayoutSubviews does not exist, use the following instead
override func viewDidAppear(animated: Bool)
This fixed it for me
The idea of why scroll view is not scrolling because you set the content size for scrolling less than the size of the scroll view, which is wrong.
You should set the content size bigger than the size of your scroll view to navigate through it while scrolling.
The same idea with zooming, you set the min and max value for zooming which will applied through zooming action.
welcome :)
One small addition, all above are the actual reasons why your scroll view might not be scrolling but sometimes mindlessly this could be the reason specially when scrollview is added through code and not IB, you might have added your subviews to the parent view and not to the scrollview this causes the subview to not scroll
and do keep the content size set and bigger than parent view frame (duhh!!)
I made it working at my first try. With auto layout and everything, no additional code. Then a collection view went banana, crashing at run time, I couldn't find what was wrong, so I deleted and recreated it (I am using Xcode 10 Beta 4. It felt like a bug) and then the scrolling was gone. The Collection view worked again, though!
Many hours later.. this is what fixed it for me. I had the following layout:
UIView
Safe Area
Scroll view
Content view
It's all in the constraints. Safe Area is automatically defined by the system. In the worst case remove all constraints for scroll and content views and do not have IB resetting/creating them for you. Make them manually, it works.
For Scroll view I did: Align Trailing/Top to Safe Area. Equal Width/Height to Safe area.
For Content view I did: Align Trailing/Leading/Top/Bottom to Superview (the scroll view)
basically the concept is to have Content view fitting Scrollview, which is fitting Safe Area.
But as such it didn't work. Content view missed the height. I tried all I could and the only one doing the trick has been a Content view height created control-dragging Content view.. to itself. That defined a fixed height, which value has been computed from the Size of the the view controller (defined as freeform, longer than the real display, to containing all my subviews) and finally it worked again!
Add the UIScrollViewDelegate and adding the following code to the viewDidAppear method fixed it for me.
#interface testScrollViewController () <UIScrollViewDelegate>
-(void)viewDidAppear:(BOOL)animated {
self.scrollView.delegate = self;
self.scrollView.scrollEnabled = YES;
self.scrollView.contentSize = CGSizeMake(375, 800);
}
My issue was resolved by:
setting the contentSize on the scrollView to a large height
BUT also I had to fix top and/or bottom constraints on views within the scrollView, which meant the scroll indicators showed on screen but the content did not scroll
Once I removed top and/or bottom constraints bound to the safe area and/or superview, the views inside the scrollView could scroll again and didn't stay fixed to the top of bottom of the screen!
Hope this stops someone else from hours of pain with this particular issue.
yet another fun case:
scrollview.superview.userInteractionEnabled must be true
I wasted 2+hrs chasing this just to figure out the parent
is UIImageView which, naturally, has userInteractionEnabled == false
Something that wasn't mentioned before!
Make sure your outlet was correctly connected to the scrollView! It should have a filled circle, but even if you have filled circle, scrollView may not been connected - so double check! Hover over the circle and see if the actual scrollview gets highlighted! (This was a case for me)
//Connect below well to the scrollView in the storyBoard
#property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
Alot of the time the code is correct if you have followed a tutorial but what many beginners do not know is that the scrollView is NOT going to scroll normally through the simulator. It is suppose to scroll only when you press down on the mousepad and simultaneously scroll. Many Experienced XCode/Swift/Obj-C users are so use to doing this and so they do not know how it could possibly be overlooked by beginners. Ciao :-)
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
// Do any additional setup after the view
}
override func viewWillLayoutSubviews(){
super.viewWillLayoutSubviews()
scrollView.contentSize = CGSize(width: 375, height: 800)
}
This code will work perfectly fine as long as you do what I said up above
If none of the other solutions work for you, double check that your scroll view actually is a UIScrollView in Interface Builder.
At some point in the last few days, my UIScrollView spontaneously changed type to a UIView, even though its class said UIScrollView in the inspector. I'm using Xcode 5.1 (5B130a).
You can either create a new scroll view and copy the measurements, settings and constraints from the old view, or you can manually change your view to a UIScrollView in the xib file. I did a compare and found the following differences:
Original:
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" directionalLockEnabled="YES" bounces="NO" pagingEnabled="YES" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Wsk-WB-LMH">
...
</scrollView>
After type spontaneously changed:
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" customClass="UIScrollView" id="qRn-TP-cXd">
...
</view>
So I replaced the <view> line with my original <scrollView> line.
I also replaced the view's close tag </view> with </scrollView>.
Be sure to keep the id the same as the current view, in this case: id="qRn-TP-cXd".
I also had to flush the xib from Xcode's cache by deleting the app's derived data:
Xcode->Window->Organizer->Projects, choose your project, on the Derived Data line, click Delete...
Or if using a device:
Xcode->Window->Organizer->Device, choose your device->Applications, choose your app, click (-)
Now clean the project, and remove the app from the simulator/device:
Xcode->Product->Clean
iOS Simulator/device->press and hold the app->click the (X) to remove it
You should then be able to build and run your app and have scrolling functionality again.
P.S. I didn't have to set the scroll view's content size in viewDidLayoutSubviews or turn off auto layout, but YMMV.
If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.
For example:
containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;
You will be able to see the scrollView but it won't receive user interactions.
adding the following code in viewDidLayoutSubviews worked for me with Autolayout. After trying all the answers:
- (void)viewDidLayoutSubviews
{
self.activationScrollView.contentSize = CGSizeMake(IPHONE_SCREEN_WIDTH, 620);
}
//set the height of content size as required
The straightforward programmatically way
To wrap it up
Create a UIScrollView
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
Use a Single Child View to Hold All of Your Content Subviews
private lazy var contentView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
Add your views
contentView.addSubview(firstSubView)
contentView.addSubview(lastSubView)
scrollView.addSubview(contentView)
view.addSubview(scrollView)
Usually, you only want your content to scroll in one direction. In most cases to scroll vertically. Therefore set the width of the content view to be the width of the scroll view.
NSLayoutConstraint.activate([
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
Attach four constraints (top, bottom, left, right) from our single content view to the scroll view.
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
Make sure you have constraints attached to all four sides of the content view so that it will expand to the size of your content.
// After Adding your subviews to the contentView make sure you've those two constraints set:
firstSubView.topAnchor.constraint(equalTo: contentView.topAnchor),
.
.
.
lastSubView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])
Reference: Using UIScrollView with Auto Layout in iOS
After failing with the provided answers in this thread, I stumbled upon this article with the solution.
There are two things not intuitive about setting up the scrollview with autolayout:
The constraints you set up as margin between the contentview and scrollview do not influence the size of the contentview. They really are margins. And to make it work, the contentview should have a fixed size.
The trick to the fixed size is that you can set the width of the contentview equal to that of the scrollview's parent. Just select both views in the tree on the left and add the equal widths constraint.
This is the gist of that article. For a complete explanation, including illustrations, check it out.
I found that with this AutoLayout issue... if I just make the ViewController use UIView instead of UIScrollView for the class... then just add a UIScrollView myself... that it works.
I had the same issue in IB.
After setting the leading, trailing, top and bottom of the scrollView to its superView. I made the following changes to make the containerView scrollable, which worked.
To make the scrollView only scroll on horizontal direction make the constraint with scrollView's centerY = ContainerView's centerY
and to make it vertically scrollable make the scrollView's centerX = ContainerView's centerX
You don’t have to set the content size of the scroll view.
Technical Note TN2154
In case someone made the same mistake like me, I'd like to share my case.
In my case, I mistakenly add a constraint to one of the subviews of scrollview which makes the subview's space to the topLayoutGuide fixed, thus it's location can't be changed, so the scrollview can't be scrolled.

Resources