簡體   English   中英

如何使用swift在UICollectionView單元格中加載自定義單元格(xib)

[英]How to load custom cell ( xib) in UICollectionView cell using swift

我使用 Swift 創建了一個小示例項目。 我創建了一個“MyCustomView”作為xib,其中包含標簽、按鈕和imageView,如下面的代碼所示:

import UIKit

@IBDesignable class MyCustomView: UIView {

    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var btnClick: UIButton!
    @IBOutlet weak var myImageView: UIImageView!

    var view:UIView!

    @IBInspectable
    var mytitleLabelText: String? {
        get {
            return lblName.text
        }
        set(mytitleLabelText) {
            lblName.text = mytitleLabelText
        }
    }

    @IBInspectable
    var myCustomImage:UIImage? {
        get {
            return myImageView.image
        }
        set(myCustomImage) {
            myImageView.image = myCustomImage
        }
    }


    override init(frame : CGRect)
    {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }


    func xibSetup()
    {
        view = loadViewFromNib()
        view.frame = self.bounds

        // not sure about this ?
        view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
        addSubview(view)
    }


    func loadViewFromNib() -> UIView {

        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "MyCustomView", bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

        return view
    }
}

附上xib的圖片以供參考。 截圖

在 StoryBoard -> ViewController 添加 UIViewCollection,如下圖所示。 在此視圖集合中,我需要橙色單元格來包含要在運行時加載的自定義 xib。

我如何實現這一目標?

在此處輸入圖片說明

Sandeep 建議的新修改代碼

// 1 導入 UIKit

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView.register(UINib(nibName: "MyCustomView", bundle: nil), forCellWithReuseIdentifier: "myCell")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell : MyCustomView = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) as! MyCustomView

        cell.lblName.text = "MyNewName"
        return cell
    }
}

// 2 導入 UIKit

@IBDesignable class MyCustomView: UICollectionViewCell {

    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var btnClick: UIButton!
    @IBOutlet weak var myImageView: UIImageView!

    var view:UIView!

    @IBInspectable
    var mytitleLabelText: String? {
        get {
            return lblName.text
        }
        set(mytitleLabelText) {
            lblName.text = mytitleLabelText
        }
    }

    @IBInspectable
    var myCustomImage:UIImage? {
        get {
            return myImageView.image
        }
        set(myCustomImage) {
            myImageView.image = myCustomImage
        }
    }

}

這是你可以做的,

  1. 將您的MyCustomView類更改為 UICollectionViewCell 而不是 UIView 的子類。

  2. 刪除override init(frame : CGRect)required init?(coder aDecoder: NSCoder)func xibSetup()func loadViewFromNib() -> UIView from MyCustomView

  3. 我真的無法理解你是如何將你的 setter 和 getter 用於 mytitleLabelText 和 myCustomImage。 如果它沒有用,也擺脫它。

  4. 最后,您將只剩下 MyCustomView 中的 IBOutlets。

  5. 為了更好的編碼實踐,將名稱從 MyCustomView 更改為 MyCustomCell(可選)

  6. 轉到您的 xib,選擇 xib 並將其類設置為 MyCustomView。

在此處輸入圖片說明

  1. 在同一屏幕中,將文件所有者更改為托管 collectionView 的 yourView 控制器

在此處輸入圖片說明

  1. 在您的 viewController 的 ViewDidLoad 中注冊您的筆尖。
self.collectionView.registerNib(UINib(nibName: "your_xib_name", bundle: nil), forCellWithReuseIdentifier: "your_reusable_identifier")
  1. 在 cellForItemAtIndexPath 中,
let cell : MyCustomView = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) as! MyCustomView
cell.lblName.text = "bla bla" //access your Cell's IBOutlets
return cell
  1. 最后,為了控制單元格的大小,要么覆蓋 collectionView 的委托,要么只需轉到您的 collectionView 中選擇 collectionCell 並拖動它以匹配您的維度:) 就是這樣:)

快樂編碼。 搜索教程以更好地理解。 我無法解釋所有代表,因為我最終會在這里寫一篇博客。

快樂編碼

對於 Swift 4.0

viewDidLoad 中

//custom collectionViewCell
mainCollectionView.register(UINib(nibName: "your_customcell_name", bundle: nil), forCellWithReuseIdentifier: "your_customcell_identifier")

cellForItemAt indexPath 中

let cell : <your_customcell_name> = mainCollectionView.dequeueReusableCell(withReuseIdentifier: "your_customcell_identifier", for: indexPath) as! <your_customcell_name>

並且不要忘記在 xib 部分為您的自定義單元格設置標識符。

如果您必須注冊多個單元格,則采用一種方法。

extension UICollectionViewCell {

    static func register(for collectionView: UICollectionView)  {
        let cellName = String(describing: self)
        let cellIdentifier = cellName + "Identifier"
        let cellNib = UINib(nibName: String(describing: self), bundle: nil)
        collectionView.register(cellNib, forCellWithReuseIdentifier: cellIdentifier)
    }
}

使用步驟

  1. 將您的 Cell 標識符命名為"YourcellName" + "Identifier"例如: CustomCellIdentifier如果您的 Cell 名稱是 CustomCell。

  2. CustomCell.register(for: collectionView)

對於 viewDidLoad 中的 Swift 4.2

 self.collectionView.register(UINib(nibName: "your_xib_name", bundle: nil), forCellWithReuseIdentifier: "your_reusable_identifier")

在 cellForItemAt 索引路徑中:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "your_reusable_identifier", for: indexPath) as! MyCustomView

當然,正如@Raj Aryan 所說:不要忘記在 xib 部分為您的自定義單元格設置標識符。

暫無
暫無

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

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