我在 Storyboard上有一个 UIImageView,具有固定高度和前导、顶部和尾随约束。我以编程方式修改其 alpha 及其顶部常量,以实现视差并随着不相关的 ScrollView 向上平移而淡出。但是,每当我将此 imageView 的图像设置为新值时,其顶部约束和 alpha 都会重置为其 Storyboard 值。
代码片段如下:
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageViewTop: NSLayoutConstraint!
extension ContentTableController: UIScrollViewDelegate {
/* Creating parallax by modifying the top constant,
and also fading out image as scrollView scrolls up.
Note the imageView is NOT in the scrollView in question. */
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let height = featuredPoster.frame.size.height
let percentScrolled: CGFloat = max(1 - offsetY / height, 0)
let parallaxFraction: CGFloat = 0.3
imageView.alpha = percentScrolled
imageViewTop.constant = -offsetY * parallaxFraction
}
...
}
...
// Called elsewhere
func setsImage() {
// setting its image resets the view's alpha and the value of its top constant
imageView.image = nil // setting to nil, but could be any value
}
最佳答案
PEBCAK
scrollViewDidScroll(...) 如果您有不同的 ScrollView 调用相同的委托(delegate)方法,则应验证哪个 ScrollView 进行调用。
在本例中,我有一个 UICollectionView,其委托(delegate)已设置。请注意,UICollectionViewDelegate 包含 UIScrollViewDelegae。
解决方案是
// The scrollView that you expect is calling the delegate method.
var desiredScrollView: UIScrollView!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//Verify this is the correct scrollView to trigger this code
guard scrollView == desiredScrollView else { return }
let offsetY = scrollView.contentOffset.y
let height = featuredPoster.frame.size.height
let percentScrolled: CGFloat = max(1 - offsetY / height, 0)
let parallaxFraction: CGFloat = 0.3
imageView.alpha = percentScrolled
imageViewTop.constant = -offsetY * parallaxFraction
}
关于ios - 设置图像时 UIImageView 的属性和约束会重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46778513/