How to make UILabel position fixed? - ios

I dragged a "Label" object into a scene in my storyboard in Xcode's Interface Builder.
The problem is that the Label is "pinned" to the top of the screen, so that when I scroll down in the View Controller, the Label is always located at the top of the screen.
What I want instead is for the Label to disappear when I scroll down and re-appear when I scroll back up. I don't want the Label to scroll at all. I want its position to be completely fixed.
I found this answer but I don't recognize the screen capture in Xcode 8.2.1.
Here is the View Controller structure:

Try this:
#interface ViewController () <UIScrollViewDelegate>
#property (nonatomic, weak) IBOutlet UILabel *fadingLabel;
#end
#implementation ViewController
#pragma mark - UIScrollViewDelegate
/* For this method to get called, make sure you set the delegate of your table view to this view controller.*/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (!self.fadingLabel)
return;
CGFloat labelHeight = CGRectGetHeight(self.fadingLabel.frame);
CGFloat alpha = 1.0f - (scrollView.contentOffset.y / labelHeight);
[self.fadingLabel setAlpha:alpha];
}
#end
Here's the swift translation:
class ViewController: UIViewController, UIScrollViewDelegate {
private weak var fadingLabel: UILabel?
// MARK: - UIScrollViewDelegate
/* For this method to get called, make sure you set the delegate of your table view to this view controller.*/
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let label = self.fadingLabel else {
return
}
let labelHeight: CGFloat = label.frame.height
let alpha: CGFloat = 1.0 - (scrollView.contentOffset.y / labelHeight)
label.alpha = alpha
}
}

You should implement UIScrollViewDelegate and hide/show the label according to the vertical content offset of your scroll view in scrollViewDidScroll(_:).
func scrollViewDidScroll(_ scrollView: UIScrollView) {
label.isHidden = scrollView.contentOffset.y > 50
}
Don't forget to set the delegate of your scroll view:
scrollView.delegate = self

Related

Custom header content animate while scrolling in swift

I have created custom header but I don't know how to animate while scrolling.
Please check below image and let me know how to animate while scrolling.
This animated header in Fotmob app.
First of all add header view as UIvVew and add UIScrollView or UITableView below headerView same as screenshot and follow below step.
set a fixed height constraint to the header view (125 for example) and attach it to top, left and right.
make the UIScrollView below to use all the available space so set to zero top, bottom, left and right constraints.
 connect the header view height constraint to the ViewController in order to have something like:
#IBOutlet var headerViewHeightConstraint: NSLayoutConstraint!
set the UIScrollView delegate to the ViewController
declare two properties to limit the maximum and the minimum height of the header view, fox example:
let headerViewMaxHeight: CGFloat = 125
let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height
The entire workaround is based on update the header view height constraint while the UIScrollView is scrolling, so let’s implement the UIScrollViewDelegate and the most important delegate for our case, the scrollViewDidScroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height
let yPos = mainScrollView.contentOffset.y
let newHeaderViewHeight: CGFloat = headerViewHeightConstraint.constant - yPos
if newHeaderViewHeight > headerViewMaxHeight {
// Here, Manage Your Score Format View
headerViewHeightConstraint.constant = max(headerViewMaxHeight, newHeaderViewHeight)
} else if newHeaderViewHeight < headerViewMinHeight {
headerViewHeightConstraint.constant = headerViewMinHeight
} else {
headerViewHeightConstraint.constant = newHeaderViewHeight
scrollView.contentOffset.y = 0 // block scroll view
}
}
I have created the same, Check the below image
Overview
TableView
Sample MVVM pattern
Swift 5.0 above
Xcode 11 above
Find the GIT URL for code
HeaderAnimation

Why does View A with bottom constraints not move when View B changes

I have a Button inside a UIView. Set up with bottom constraints. Once I change the height of the UIView, I expect the Button to move since it has (equal) Constraints to the Bottom.
Bottom Constraints set:
Button nested inside UIView.
Once I move the UITableView, the following code get's called:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = -scrollView.contentOffset.y
if offset > 100 {
bgView.frame.size.height = offset
bgView.layoutIfNeeded() // not a solution
getBtn.layoutIfNeeded() // not a solution
}
view.bringSubview(toFront: tableView)
if scrollView.contentOffset.y == -100.0 {
view.bringSubview(toFront: bgView)
}
}
The Button keeps its position.
What am I missing? Help is very appreciated.
As requested:
Create an IBOutlet for bgView Height Constraint and then change its constant
#IBOutlet weak var bgViewHeightConstraint: NSLayoutConstraint!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = -scrollView.contentOffset.y
if offset > 100 {
bgViewHeightConstraint.constant = offset
view.layoutIfNeeded()
}
...
}

UITextView is not scrolled to top when loaded

When I have text that does not fill the UITextView, it is scrolled to the top working as intended. When there is more text than will fit on screen, the UITextView is scrolled to the middle of the text, rather than the top.
Here are some potentially relevant details:
In viewDidLoad to give some padding on top and bottom of UITextView:
self.mainTextView.textContainerInset = UIEdgeInsetsMake(90, 0, 70, 0);
The UITextView uses auto layout to anchor it 20px from top, bottom and each side of the screen (done in IB) to allow for different screen sizes and orientations.
I can still scroll it with my finger once its loaded.
EDIT
I found that removing the auto layout constraints and then fixing the width only seems to fix the issue, but only for that screen width.
add the following function to your view controller class...
Swift 3
override func viewDidLayoutSubviews() {
self.mainTextView.setContentOffset(.zero, animated: false)
}
Swift 2.1
override func viewDidLayoutSubviews() {
self.mainTextView.setContentOffset(CGPointZero, animated: false)
}
Objective C
- (void)viewDidLayoutSubviews {
[self.mainTextView setContentOffset:CGPointZero animated:NO];
}
UITextView is a subclass of UIScrollView, so you can use its methods. If all you want to do is ensure that it's scrolled to the top, then wherever the text is added try:
[self.mainTextView setContentOffset:CGPointZero animated:NO];
EDIT: AutoLayout with any kind of scrollview gets wonky fast. That setting a fixed width solves it isn't surprising. If it doesn't work in -viewDidLayoutSubviews then that is odd. Setting a layout constraint manually may work. First create the constraints in IB:
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewWidthConstraint;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
then in the ViewController
-(void)updateViewConstraints {
self.textViewWidthConstraint.constant = self.view.frame.size.width - 40.0f;
self.textViewHeightConstraint.constant = self.view.frame.size.height - 40.0f;
[super updateViewConstraints];
}
May still be necessary to setContentOffset in -viewDidLayoutSubviews.
(Another method would be to create a layout constraint for "'equal' widths" and "'equal' heights" between the textView and its superView, with a constant of "-40". It's only 'equal' if the constant is zero, otherwise it adjusts by the constant. But because you can only add this constraint to a view that constraints both views, you can't do this in IB.)
You may ask yourself, if I have to do this, what's the point of AutoLayout? I've studied AutoLayout in depth, and that is an excellent question.
Swift
self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
Objective-C
[self.textView scrollRangeToVisible:(NSMakeRange(0, 0))];
i had same issue! Reset to suggested constrains and just put (y offset)
#IBOutlet weak var textContent: UITextView!
override func viewDidLoad() {
textContent.scrollsToTop = true
var contentHeight = textContent.contentSize.height
var offSet = textContent.contentOffset.x
var contentOffset = contentHeight - offSet
textContent.contentOffset = CGPointMake(0, -contentOffset)
}
For iOS9 and later the textview even on viewWillAppear: is coming with CGRect(0,0,1000,1000). In order for this to work you have to call in viewWillAppear:
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
// * Your code here
After that the textview will have correct CGRect data and you can perform any scrolling operation you may need.
The problem with putting code in viewDidLayoutSubviews and viewWillLayoutSubviews is that these methods are called a lot (during device rotation, resizing views etc ...). If you're reading something from text view, and you rotate the device, you expect that the part of the content you're viewing stays on screen. You do not expect that it scrolls back to top.
Instead of scrolling the content to top, try to keep text view's scrollEnabled property set to NO (false), and turn it back on in viewDidAppear.
If you don't wanna mess with constraints:
override func updateViewConstraints() {
super.updateViewConstraints()
}
override func viewDidLayoutSubviews() {
self.textLabel.setContentOffset(CGPointZero, animated: false)
}
This is an interesting bug. In our project, this is only occurring on devices with an iPhone 5-size screen. It appears that the textview contentOffset changes at some point during the view controller lifecycle. In viewDidLoad and viewWillAppear the textview's contentOffset is 0,0, and by viewDidAppear it's changed. You can see it happening in viewWillLayoutSubviews. Constraints appear to be set up correctly.
This will ensure you don't call a scrolling method unless it's needed:
if textView.contentOffset.y > 0 {
textView.contentOffset = CGPoint(x: 0, y: 0)
// Or use scrollRectToVisible, scrollRangeToVisible, etc.
}
Swift
override func viewDidLoad() {
super.viewDidLoad()
textView.isScrollEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.isScrollEnabled = true
}
For me this works in a different way, I tried all things mentioned above but none of the worked in func viewWillAppear(_ animated: Bool). Which eventually makes textView scrolled up, and in func viewDidAppear(_ animated: Bool) it would scroll after screen appeared.
Below worked for me but got some constraint related issue with keyboard up and down.
override func viewDidLayoutSubviews() {
self.textView.setContentOffset(.zero, animated: false)
}
Below worked as expectation:
override func viewDidLoad() {
super.viewDidLoad()
self.textView.scrollsToTop = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.layoutIfNeeded()
self.textView.setContentOffset(.zero, animated: false)
}
David Rectors answer in Objective C:
#import "TopTextView.h"
#implementation TopTextView
bool scrolled = NO;
- (void) layoutSubviews
{
[super layoutSubviews];
if (!scrolled) {
[self setContentOffset:CGPointMake(0, 0) animated:NO];
scrolled = YES;
}
}
#end
It seems like a terrible idea to handle this issue in code in the view controller because: A. The view controller isn't making any mistake or doing anything wrong, and B, if you have more than one view controller with a wrongly scrolled text view, you end up with redundant code. The solution should be to write code that exists in the text view class. My solution works with Interface Builder where I simply select a custom class for the UITextView and use this class:
import Foundation
import UIKit
class TopTextView: UITextView {
var scrolled = false
override func layoutSubviews() {
super.layoutSubviews()
if scrolled { return }
setContentOffset(.zero, animated: false)
scrolled = true
}
}
This worked for me. I happen to have a view controller with a child view with a UITextView as a child of that view, not with a UITextView as the child of the view controller. I don't know how well this works if the text view is under top or bottom bars but since no edge insets are touched, this should work.
In my case I had to do it like this:
textView.setContentOffset(CGPoint(x: 0, y: -self.textView.adjustedContentInset.top), animated: false)
because the texview was underneath the navigation bar and had an adjusted inset

iOS how to check if go to the bottom of webView

Is there any event I can notify the supper view?
I try the scrollViewDidScroll. But it don't be called.
-(void)scrollViewDidScroll: (UIScrollView*)scrollView
{
NSLog(#"At the bottom...");
}
You must set the delegate of scrollview which in the webview to self first. So that, scrollViewDidScroll: could be call when you scroll the webview. So, try this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.webview.scrollview.delegate = self;
}
- (void)scrollViewDidScroll:(UIScrollView*)scrollview
{
CGPoint offset = scrollView.contentOffset;
CGRect bounds = scrollView.bounds;
UIEdgeInsets inset = scrollView.contentInset;
CGFloat currentOffset = offset.y + bounds.size.height - inset.bottom;
if (currentOffset - scrollView.contentSize.height <= 0)
{
NSLog(#"At the bottom...");
}
}
If you have an instance of webView, you can get the reference of its scrollView by doing,
webView.scrollView. Set its delegate to self like so:
webView.scrollView.delegate = self;
Now, make sure you have implemented UIScrollViewDelegate in your class where you have an instance of the webView. Implement the below the code that tells you whether you have reached the bottom.
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
if (bottomEdge >= scrollView.contentSize.height) {
//This means that you have reached the end.
}
}
To get the call in scrollView delegate methods you need to assign the delegate for webview scroll view like this:
webview.scrollView.delegate = self;
Also Conform the UIScrollViewDelegate in .h file like this:
#interface MyController : UIViewController <UIScrollViewDelegate>
#end
If anyone is interested on how this is done in Swift 4, here it is:
Set the webviews' scrollView delegate to self in viewDidLoad() self.webView.scrollView.delegate = self
Extend your class from UIScrollViewDelegate
Implement the method scrollViewDidScroll() which will handle the scroll events
(this particular implementation is used to check if the user has scrolled to the bottom of the webview's content)
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let bottom = scrollView.contentOffset.y + scrollView.frame.size.height
if (bottom >= scrollView.contentSize.height) {
// Do something here
}
}

UICollectionView: how to detect when scrolling has stopped

I'm using a UICollectionView to scroll through a set of thumbnails quickly. Once scrolling ends, I'd like to display a larger hi-res version of the current thumbnail.
How can I detect when the user has completed scrolling? I do implement didEndDisplayingCell, but that only tells me when a particular cell has scrolled off; it doesn't tell me when the scroll motion actually completes.
NS_CLASS_AVAILABLE_IOS(6_0) #interface UICollectionView : UIScrollView
UICollectionView is a subclass of UIScrollView. So if you have set the delegate and implemented UIScrollViewDelegate, you should be able to detect this the same way as UIScrollView.
For eg:-
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
As per documentation, the above method should tell when the scroll view has ended decelerating the scrolling movement.
Just to cover your bases you should implement both these UIScrollViewDelegate methods.
In some cases there may not be a deceleration (and scrollViewDidEndDecelerating would not be called), for e.g., the page is fully scrolled in place. In those case do your update right there in scrollViewDidEndDragging.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate) {
[self updateStuff];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self updateStuff];
}
An important fact to note here.
This method gets called on User initiated scrolls (i.e a Pan gesture):
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
or in Swift:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
On the other hand, this one gets called on all manually (programatically) initiated scrolls (like scrollRectToVisible or scrollToItemAtIndexPath):
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
or in Swift:
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)
Swift 3 version of Abey M and D6mi 's answers:
When scroll is caused by user action
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if (!decelerate) {
//cause by user
print("SCROLL scrollViewDidEndDragging")
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//caused by user
print("SCROLL scrollViewDidEndDecelerating")
}
When scroll is caused by code action (programmatically): (like "scrollRectToVisible" or "scrollToItemAtIndexPath")
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
//caused by code
print("SCROLL scrollViewDidEndScrollingAnimation")
}
Notes:
Put these functions in your UIScrollViewDelegate or UICollectionViewDelegate delegate.
if you don't have a separate delegate, make your current class extend a UIScrollViewDelegate op top of your class file
.
open class MyClass: NSObject , UICollectionViewDelegate
and somewhere in your viewWillAppear make the class its own delegate
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// ...
self.myScrollView.delegate = self
// ...
}
Swift 3 version:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// Your code here
}
if you want to use the visible indexpath:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self scrollingFinish];
}
- (void)scrollingFinish {
if([self.collectionView indexPathsForVisibleSupplementaryElementsOfKind:UICollectionElementKindSectionHeader]){
NSIndexPath *firstVisibleIndexPath = [[self.collectionView indexPathsForVisibleSupplementaryElementsOfKind:UICollectionElementKindSectionHeader] firstObject];
[self.collectionView scrollToItemAtIndexPath:firstVisibleIndexPath atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
}
Get your collection view index and Dont forget to import UISCrollViewDelegate in your class
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let xPoint = scrollView.contentOffset.x + scrollView.frame.width / 2
let yPoint = scrollView.frame.height / 2
let center = CGPoint(x: xPoint, y: yPoint)
if let ip = self.collectionView.indexPathForItem(at: center) {
pageIndex = ip.row
}
print(">>>>>>>>>\(pageIndex)")
}

Resources