簡體   English   中英

如何在 UICollectionViewCell UICollectionView 中設置圖像 Swift

[英]How to image setup in UICollectionView in UICollectionViewCell Swift

我正在嘗試在 collectionView 中設置水平 alignment 中的圖像,但它無法正常工作。 請檢查隨附的屏幕截圖。

查看 Controller 代碼:-

import UIKit

class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {

@IBOutlet weak var texting1: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    self.texting1.register(UINib(nibName:"CollectionViewCell1", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell1")
    self.texting1.delegate = self
    self.texting1.dataSource = self
    texting1.backgroundColor = .red
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}

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

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: self.view.frame.width, height: 120)
  }
}

Output:-圖片

CollectionViewCell1 代碼:-

import UIKit

class CollectionViewCell1: UICollectionViewCell,UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {

@IBOutlet weak var userImageColectionView: UICollectionView!

override func awakeFromNib() {
    super.awakeFromNib()
    self.userImageColectionView.register(UINib(nibName:"CollectionViewCell2", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell2")
    userImageColectionView.delegate = self
    userImageColectionView.dataSource = self
    userImageColectionView.backgroundColor = .black
}
    
var items = ["1", "2", "3", "4"]

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

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

// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.item)!")
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: 70, height: 60);
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return -10
  }
}

Xib 屏幕截圖:-圖片

CollectionViewCell2 代碼:-

class CollectionViewCell2: UICollectionViewCell {

@IBOutlet weak var imguserView: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
    imguserView.image = UIImage(systemName: "person.crop.circle")
   }
}

Xib 屏幕截圖:-圖片

我的目標:-圖片

有人可以向我解釋如何在水平 alignment 的集合視圖下顯示圖像並根據單元格圖像計數設置動態寬度,我已經嘗試通過上面實現但還沒有結果。

任何幫助將不勝感激。

提前致謝。

使用集合視圖的情況下執行此操作的一種方法是為“單元格視圖”創建約束的“水平鏈”。

例如,如果我們有 3 個圖像視圖 - 紅色、綠色和藍色 - 具有以下約束:

    NSLayoutConstraint.activate([
        red.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0),
        green.leadingAnchor.constraint(equalTo: red.trailingAnchor, constant: 10.0),
        blue.leadingAnchor.constraint(equalTo: green.trailingAnchor, constant: 10.0),
    ])

它看起來像這樣:

在此處輸入圖像描述

如果我們改為使用常量:

    NSLayoutConstraint.activate([
        red.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0),
        green.leadingAnchor.constraint(equalTo: red.trailingAnchor, constant: -20.0),
        blue.leadingAnchor.constraint(equalTo: green.trailingAnchor, constant: -20.0),
    ])
    

它看起來像這樣:

在此處輸入圖像描述

所以我們可以創建一個自定義的UIView子類來為我們處理所有這些——例如:

class OverlapView: UIView {
    
    public var overlap: CGFloat = -30 { didSet { setNeedsLayout() } }
    
    public var cellViews: [UIView] = [] {
        didSet {
            // clear out any existing subviews
            subviews.forEach { v in
                v.removeFromSuperview()
            }
            cellViews.forEach { v in
                // in case it wasn't set by the caller
                v.translatesAutoresizingMaskIntoConstraints = false
                addSubview(v)
                // center it vertically
                v.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
                // we want the overlap to go from left-to-right
                sendSubviewToBack(v)
            }
            setNeedsLayout()
        }
    }
    
    private var horizontalConstraints: [NSLayoutConstraint] = []
    
    override func layoutSubviews() {
        super.layoutSubviews()

        guard cellViews.count > 0 else { return }

        // de-activate any existing horizontal constraints
        NSLayoutConstraint.deactivate(horizontalConstraints)
        
        var prevView: UIView!
        cellViews.forEach { v in
            // if it's the first one
            if prevView == nil {
                horizontalConstraints.append(v.leadingAnchor.constraint(equalTo: leadingAnchor))
            } else {
                horizontalConstraints.append(v.leadingAnchor.constraint(equalTo: prevView.trailingAnchor, constant: overlap))
            }
            prevView = v
        }
        // constrain last view's trailing
        horizontalConstraints.append(prevView.trailingAnchor.constraint(equalTo: trailingAnchor))

        // activate the udpated constraints
        NSLayoutConstraint.activate(horizontalConstraints)
    }
}

這是一個樣本 controller 證明:

class OverlapTestVC: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let testView = OverlapView()
        testView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(testView)
        
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            testView.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),
            testView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 16.0),
            testView.heightAnchor.constraint(equalToConstant: 70.0),
            
            // no trailing or width constraint
            //  width will be determined by the number of "cells"
        ])

        // let's add 6 "cells" -- one for each color
        let colors: [UIColor] = [
            .systemRed, .systemGreen, .systemBlue,
            .systemYellow, .systemCyan, .magenta,
        ]
        var cellViews: [UIView] = []
        colors.forEach { c in
            if let img = UIImage(systemName: "person.crop.circle") {
                let imgView = UIImageView(image: img)
                imgView.tintColor = c
                imgView.backgroundColor = .white
                imgView.translatesAutoresizingMaskIntoConstraints = false
                // let's use a 60x60 image view
                imgView.widthAnchor.constraint(equalToConstant: 60.0).isActive = true
                imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor).isActive = true
                // we want "round" views
                imgView.layer.cornerRadius = 30.0
                imgView.layer.masksToBounds = true
                cellViews.append(imgView)
            }
        }

        testView.cellViews = cellViews
        
        // we can change the overlap value here if we don't want to use
        //  our custom view's default
        // for example:
        //testView.overlap = -40.0
        
        // so we can see the framing
        testView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

    }
    
}

Output 看起來像這樣:

在此處輸入圖像描述

(我們給自定義視圖本身一個淺灰色背景,這樣我們就可以看到它的框架。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM