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

时间:2017-10-16 20:23:54

标签: ios swift uiimageview uistoryboard nslayoutconstraint

我在故事板上有一个UIImageView,它具有固定的高度以及前导,顶部和尾随约束。我以编程方式修改其alpha及其顶部常量,以实现视差和淡出,因为无关的scrollView向上平移。但是,每当我将此imageView的图像设置为新值时,其顶部约束和alpha都会重置为其故事板值。

代码段如下:

@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
}

2 个答案:

答案 0 :(得分:0)

PEBCAK

如果您有不同的滚动视图调用相同的委托方法,

scrollViewDidScroll(...)应该验证哪个scrollView正在进行调用。

在这种情况下,我有一个UICollectionView,其委托已设置。请注意 UICollectionViewDelegate 包含 UIScrollViewDelegat e。

解决方案是

// 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
    }

答案 1 :(得分:0)

尝试降低其内容拥抱和压缩:

someImage.setContentHuggingPriority(UILayoutPriority(rawValue: 249), for: .horizontal)
someImage.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 249), for: .horizontal)
someImage.setContentHuggingPriority(UILayoutPriority(rawValue: 249), for: .vertical)
someImage.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 249), for: .vertical)