2017-04-25 44 views
1

好日子,我只在Objective-C或Swift 2中看到過這個例子,但還沒有在Swift 3中運行過Xcode 8.我的情況是我有一個帶有一套圖像,我希望它們在用戶點擊它們時被放大。這裏是我的代碼:Swift 3:在CollectionView中選擇時放大圖像

@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 

    } 

順便說一句,我在另一個迅速類集合視圖單元代碼。下面的代碼:

class CustomCell: UICollectionViewCell { 

    @IBOutlet weak var myImage: UIImageView! 
} 

所有的圖像都顯示正常,我只需要在用戶選擇他們他們以某種方式放大。謝謝。

回答

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() 
} 
+0

謝謝!這工作。唯一的一點是它不會將圖像放在縮放視圖中(當它將其全屏顯示時)。某些圖像顯得過於接近或未完全顯示。 @Luan Tran – Angel

+0

嗨。我很樂意幫助你。您可以更改'contentMode'作爲圖片的中心。更改爲'imageView.contentMode = .center'或'imageView.contentMode = .scaleAspectFit' –

+0

完美!非常感謝。 @Luan Tran – Angel