嗨,我正在创建一个需要网格图像的应用程序。作为一个例子,我在UICollectionView的单元格中使用了一个2x2的图像网格。我想知道如何减少中间的烦人空间,并让它们具有相同的宽度和高度以适应整个屏幕。我知道我可以使用Interface builder完成此操作。然而,我想以编程的方式做到这一点,因为随着应用程序的进展,会有不同的级别和不同数量的正方形 - 可能也是10x10。我是UICollectionViews的新手。我曾参考其他许多问题,但大多数都在目标C,似乎有一些是在斯威夫特不斯威夫特工作3如何更改2x2 UICollectionView的大小并适合整个屏幕:Swift 3 Xcode 8
这里是我的全码:
import UIKit
class GameViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionView.delegate = self
collectionView.dataSource = self
let collectionViewLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
collectionViewLayout.minimumLineSpacing = 0
collectionViewLayout.minimumInteritemSpacing = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let image = cell.viewWithTag(1) as! UIImageView
image.image = #imageLiteral(resourceName: "coffee")
return cell;
}
func collectionView(_collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: self.collectionView.frame.size.width/2, height: self.collectionView.frame.size.height/2)
//this method is not getting called
}
}
我还上传的它目前是怎样一个形象,我怎么想它是─
我希望你们能帮助我 - 这将会非常有用......谢谢!
我符合UICollectionViewDelegateFlowLayout并称为sizeforitematindexpath但它没有工作。 在添加一个断点时,我意识到该方法没有被调用。那么,我在这里做什么错了。此外Xcode中给了我这样的警告 -
你可能要检查UIStackView –