Swift 3 - UICollectionView Center Cell พร้อมช่องว่างภายใน

ฉันมี UICollectionView ที่เลื่อนในแนวนอนและฉันต้องการให้เซลล์หนึ่งเซลล์ปรากฏบนหน้าจอในแต่ละครั้ง

ฉันกำลังตั้งค่าความกว้างและความสูงของเซลล์โดยทางโปรแกรมโดยใช้วิธีต่อไปนี้:

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

    let width = collectionView.bounds.size.width - 40
    let height = collectionView.bounds.size.height - 40

    cell.bounds.size = CGSize(width: CGFloat(width), height: CGFloat(height))

    return cell
}

และหลังจากดิ้นรนเพื่อหาวิธีทำงานกับสิ่งที่แทรก การเว้นวรรค ส่วนแทรก (ทั้งทางโปรแกรมและในตัวตรวจสอบใน XCode) ดูเหมือนว่าฉันไม่สามารถเข้าใจได้ว่าต้องตั้งค่าอะไรและต้องตั้งค่าที่ไหน

นี่คือไดอะแกรมของระยะห่างที่ฉันต้องการ: ป้อนคำอธิบายรูปภาพที่นี่


person Chris Schlitt    schedule 03.01.2017    source แหล่งที่มา


คำตอบ (2)


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
  return CGSize(width: UIScreen.main.bounds.width - 40, height: yourCollectionViewHeight - 40)
}

เหลือ 20 - เพิ่ม Footer Size และ Header Size ในกระดานเรื่องราวด้วย width = 20

ระยะห่างระหว่างเซลล์ - เพิ่ม Minimum Spacing ในกระดานเรื่องราว = 40

ป้อนคำอธิบายรูปภาพที่นี่

ฉันอาจมีข้อผิดพลาดและคุณจะไม่ได้เค้าโครงของคุณอย่างแน่นอน แต่ฉันหวังว่าคุณจะเข้าใจแนวคิดนี้

person JuicyFruit    schedule 03.01.2017

  1. หากคุณต้องการให้มองเห็นเซลล์เดียวบนหน้าจอในแต่ละครั้ง สิ่งสำคัญคือคุณควร เปิดใช้งาน การแบ่งหน้า สำหรับ CollectionView ของคุณ คุณสามารถทำได้อย่างรวดเร็วดังนี้:
collectionView.isPagingEnabled = true
  1. ตอนนี้ปรับคลาส ViewController ของคุณเป็น UICollectionViewDelegateFlowLayout และใช้วิธี sizeForItemAt indexPath ซึ่งจะส่งคืน CGSize สำหรับเซลล์ collectionview ของคุณ ตัวอย่างเช่น:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {    
    return CGSize(width: 200, height: 200)
}
person Ashvini    schedule 27.09.2018