【问题标题】:Swift 3: Enlarging images when selected in CollectionViewSwift 3:在 CollectionView 中选择时放大图像
【发布时间】:2017-04-25 21:06:52
【问题描述】:

美好的一天,我只在 Objective-C 或 Swift 2 中看到过这样的示例,但在运行 Xcode 8 的 Swift 3 中还没有看到。我的情况是我有一个包含一组图像的集合视图,我希望它们是当用户点击它们时放大。这是我的代码:

@IBOutlet weak var collectionView: UICollectionView!


var images = ["catPic1.jpg", "catPic2.jpg", "catPic3.jpg"]

override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        collectionView.delegate = self

        collectionView.dataSource = self

    } // end of view did load

 public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return images.count
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell" , for: indexPath) as! CustomCell

        cell.myImage.image = UIImage(named: images[indexPath.row])


        return cell

    }

顺便说一句,我在另一个 swift 类中有集合视图单元格代码。代码如下:

class CustomCell: UICollectionViewCell {

    @IBOutlet weak var myImage: UIImageView!
}

所有图像都正确显示,我只需要在用户选择它们时以某种方式放大它们。谢谢。

【问题讨论】:

    标签: ios xcode swift3 uicollectionview


    【解决方案1】:

    您可以使用另一个UIImageView 全屏查看您的图片

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
        let imageView = UIImageView(image: UIImage(named: images[indexPath.row]))
        imageView.frame = self.view.frame
        imageView.backgroundColor = .black
        imageView.contentMode = .top
        imageView.isUserInteractionEnabled = true
    
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        imageView.addGestureRecognizer(tap)
    
        self.view.addSubview(imageView)
    }
    
    // Use to back from full mode
    func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
        sender.view?.removeFromSuperview()
    }
    

    【讨论】:

    • 谢谢!这行得通。唯一的问题是它不会在缩放视图中居中图像(当它全屏显示时)。一些图像看起来太近或未完全显示。 @Luan Tran
    • 嗨。我很高兴能帮助你。您可以更改contentMode 以使图像居中。更改为imageView.contentMode = .centerimageView.contentMode = .scaleAspectFit
    • 完美!非常感谢。 @Luan Tran
    • 尝试使用 self.imageView?.contentMode = .scaleToFill
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多