我正在写一个iOS纸牌游戏。我想给用户看他手里的卡片。我找了一个CocoaPods这样做在一个好看的方式,但找不到任何,所以我决定创建这样一个视图自己使用一个水平
UICollectionView
以下是一些要求:
-
-
集合视图单元格的高度应等于集合视图的高度。我不知道怎么做。我只找到了
this question
-
集合视图单元格的宽度应等于其高度*5/7。这是卡片的W:H比率。我想我也可以通过限制来做到这一点。
-
这是我的尝试:
extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 15
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.addConstraint(NSLayoutConstraint(item: cell, attribute: .height, relatedBy: .equal, toItem: cell, attribute: .width, multiplier: 5.0 / 7.0, constant: 0))
// here I am just setting all the cells to have the same image for testing purposes
(cell.viewWithTag(1) as! UIImageView).image = someCardImage
return cell
}
}
结果:
似乎只有集合视图的约束起作用。其他的都不是。我在上面以编程方式添加的纵横比约束显然与我不知道的其他约束冲突:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x604000290810 UICollectionViewCell:0x7fd536610300.height == 0.714286*UICollectionViewCell:0x7fd536610300.width (active)>",
"<NSLayoutConstraint:0x600000292390 'UIView-Encapsulated-Layout-Height' UICollectionViewCell:0x7fd536610300.height == 99 (active)>", <---- What is this constraint?
"<NSLayoutConstraint:0x600000292340 'UIView-Encapsulated-Layout-Width' UICollectionViewCell:0x7fd536610300.width == 68 (active)>" <---- What is this constraint?
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000292390 'UIView-Encapsulated-Layout-Height' UICollectionViewCell:0x7fd536610300.height == 99 (active)>
如何创建这样一个集合视图,以满足我的需求?