Currently I have a UIView
container situated above a UITableView
. Using the inheritance from UIScrollView
, I created an IBOutlet
of the container view's leading constraint, and adjust the constraint similar to as follows:
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
if scrollView.contentOffset.y < 0
{
...
containerViewLeftConstraint.constant -= abs(scrollView.contentOffset.y) * 2
}
else
{
...
containerViewLeftConstraint.constant += abs(scrollView.contentOffset.y) * 2
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)
{
resetContainerViewSize()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
{
resetContainerViewSize()
}
func resetContainerViewSize()
{
containerViewLeftConstraint.constant = 0.0
UIView.animate(withDuration: 0.4,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: .curveEaseInOut,
animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
For demonstration, I've set the container view's backgroundColor
to red to visually see what's happening:
I've declared a var gradientLayer = CAGradientLayer()
and added it as as a sublayer to the container view like so:
func createGradientOverlay()
{
gradientLayer.frame = containerView.frame
let colors = [UIColor.black.withAlphaComponent(0.5).cgColor,
UIColor.white.cgColor]
gradientLayer.colors = colors
gradientLayer.startPoint = CGPoint(x:0.0,
y:0.5)
gradientLayer.endPoint = CGPoint(x:1.0, y:0.5);
containerView.layer.addSublayer(gradientLayer)
}
However, the result I'm getting is as shown:
The gradient layer does not stick to the bounds of the container view and appears to be floating.
I've looked at several similar questions:
- CALayers didn't get resized on its UIView's bounds change. Why?
- Auto Layout constraint on CALayer IOS
- How to get CAShapeLayer to work with constraints with swift?
- How to add a CAGradientLayer to a UIView when using programmatic constraints
All suggests using viewDidLayoutSubviews
like so:
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
gradientLayer.frame = nameContainerView.frame
}
However the gradient layer still appears to be floating and not sticking to the constraints of the container view.
I've also tried the following to no avail:
gradientLayer.frame = nameContainerView.bounds
gradientLayer.bounds = nameContainerView.bounds
gradientLayer.frame = nameContainerView.layer.bounds
gradientLayer.frame = nameContainerView.layer.frame
How can I resolve this issue?