【问题标题】:Preserve Image Aspect Ratio in UICollectionViewCell在 UICollectionViewCell 中保留图像纵横比
【发布时间】:2016-05-24 18:45:39
【问题描述】:

问题:在 UICollectionViewCell 中重新加载缓存的 UIImageView(在滚动时在 UICollectionViewController 之间切换)没有保留正确的 contentMode。

我尝试在 UIImageView 上使用 .sizeToFit() 并在每次加载时重置 .contentMode = UIViewContentMode.ScaleAspectFit,但这没有帮助。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> MyCollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! MyCollectionViewCell

    if ( indexPath.item < self.the_array?.count ){

        if ( images_cache[self.the_array![indexPath.item].src!] != nil ){
            // calling this here doesn't work
            cell.myImage.contentMode = UIViewContentMode.ScaleAspectFit
            // calling this here doesn't work either
            cell.myImage.sizeToFit()
            cell.myImage.image = images_cache[self.the_array![indexPath.item].src!]! as UIImage
        }
        else{
            if let url  = NSURL(string: "https:" + (self.the_array![indexPath.item].src)!), data = NSData(contentsOfURL: url) {
                let the_image = UIImage( data: data )
                cell.myImage.image = the_image
                images_cache[self.the_array![indexPath.item].src!] = the_image!
            }
        }
    }
    return cell
}

【问题讨论】:

    标签: swift uiimageview uicollectionview uicollectionviewcell


    【解决方案1】:

    解决方法:根据单元格的大小设置UIImage的.frame!

    cell.myImage.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)
    

    我把那行放在我有 .sizeToFit() 和/或 .contentMode 的地方,现在它可以正确保留图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-16
      • 2013-07-26
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多