我有一個顯示12個圖像的UICollectionView。圖像不適合細胞,它們正在裁剪,但我希望它們能夠適應細胞而不會被裁剪。縮放圖像以適合 - iOS
,應該使圖像比例,以適應該代碼是:
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView.image = UIImage(named: name)
這是我整個的viewController類和截圖代碼:
import UIKit
class DressingRoomViewController:
UIViewController,
UICollectionViewDelegateFlowLayout,
UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
let identifier = "cellIdentifier"
let dataSource = DataSource()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
// Notes on the equation to get the cell size:
// cells per row = 6
// cell spacing = 10
// collectionView.layout.inset = 20 (10 left, 10 right)
let cellSize = (collectionView.collectionViewLayout
.collectionViewContentSize().width - 20)/6 - 10
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20,
left: 10,
bottom: 10,
right: 10)
layout.itemSize = CGSize(width: cellSize, height: cellSize)
collectionView.collectionViewLayout = layout
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue( segue: UIStoryboardSegue,
sender: AnyObject?) {
if (segue.identifier == "dressingRoom2MyOutfits") {
let myOutfitsViewController = segue.destinationViewController
as! MyOutfitsViewController
}
}
}
// MARK:- UICollectionViewDataSource Delegate
extension DressingRoomViewController : UICollectionViewDataSource {
func numberOfSectionsInCollectionView(
collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
identifier,forIndexPath:indexPath) as! FruitCell
let fruits: [Fruit] = dataSource.fruits
let fruit = fruits[indexPath.row]
let name = fruit.name!
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView.image = UIImage(named: name)
return cell
}
}
編輯:這裏是FruitCell類,以防萬一你想知道。
class FruitCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
更改內容模式。這裏是鏈接:http://stackoverflow.com/questions/14134035/how-to-manage-uiimageview-content-mode –
@MihirOza我已經改變了UIImageView的contentMode。所以我嘗試添加UIImageView的autoresizingMask,但沒有做任何事情。 – BeniaminoBaggins
這不僅僅是您之前的重複http://stackoverflow.com/questions/32194205/uicollectionview-cells-do-not-take-up-width-of-uicollectionview? – matt