Reputation: 524
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:
Upvotes: 0
Views: 632
Reputation: 866
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
}
}
Upvotes: 1
Reputation: 58029
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
Upvotes: 0