ios - 设置图像时 UIImageView 的属性和约束会重置

标签 ios swift uiimageview uistoryboard nslayoutconstraint

我在 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/

相关文章:

ios - 在 UIImageView IOS 中加载动画 gif

ios - 清晰的 IBDesignable View 具有黑色背景

ios - 将整数从 View Controller 传递给应用程序委托(delegate)

ios - Swift:截取 viewController 的屏幕截图并在 Facebook 上分享

swift - 'sharedApplication' 不可用 : not available on iOS (App Extension) for Segmentio/Analytics Pod

ios - 如何在其父 View 中完全限制 subview (这是一个 UIImageView)?

ios - 获取 AdMob 中介 ID

ios - 获取 Facebook 好友列表?

Swift objc_getAssociatedObject 始终为零

swift - 更改导航栏按钮的颜色