【问题标题】:How to load custom cell ( xib) in UICollectionView cell using swift如何使用 swift 在 UICollectionView 单元中加载自定义单元 (xib)
【发布时间】:2016-09-15 21:01:24
【问题描述】:

我使用 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,如下图所示。在这个 viewcollection 中,我需要那个橙色单元格来包含我的自定义 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
        }
    }

}

【问题讨论】:

  • 请将 let cell : MyCustomView = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) 更改为! MyCustomView 让单元格:MyCustomView = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as!我的自定义视图

标签: ios swift ipad xib


【解决方案1】:

这是你可以做的,

  1. 将您的 MyCustomView 类更改为 UICollectionViewCell 而不是 UIView 的子类。

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

  3. 我真的无法理解您是如何将 setter 和 getter 用于 mytitleLabelText 和 myCustomImage。如果它没有用,也摆脱它。

  4. 最后,您将在 MyCustomView 中只剩下 IBOutlets。

  5. 为了更好的编码习惯,将名称从 MyCustomView 更改为 MyCustomCell(可选)

  6. 转到您的 xib,选择 xib 并将其类设置为 MyCustomView。

  1. 在同一屏幕中将文件所有者更改为托管 collectionView 的视图控制器

  1. 在 viewController 的 ViewDidLoad 中注册您的 nib。
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 并将其拖动以匹配您的尺寸:) 就是这样 :)

愉快的编码。搜索教程以获得更好的理解。我无法解释所有代表,因为我最终会在这里写一篇博客。

愉快的编码

【讨论】:

  • 感谢 Sandeep 一步一步的解释。我会按照上面的建议尝试。
  • @yannis-p :很抱歉现在看到你的消息,很长一段时间没有真正活跃在 SO 上,我希望你现在得到你的答案,但如果没有,如果你想使用相同的跨多个 ViewControllers 的 xib/cell 您可以跳过第 7 步 :) 这一切都按照其他步骤进行,不应该有任何问题 :)
  • 我实际上只是最终使单元格/演示文稿可定制,但我正在为许多不同的屏幕重用相同的逻辑,只是不同的内容更好。但是,当我决定重用 UI 时,感谢您的回答将在未来有用:)
  • 您的分步操作完美。谢谢! (iOS 13 / 斯威夫特 5)
  • registerNib 已重命名为 register。步骤 #8 的小更新 ;)
【解决方案2】:

对于 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 部分为您的自定义单元格设置标识符。

【讨论】:

  • 太棒了!非常感谢!
【解决方案3】:

如果您必须注册多个单元格,则采用一条线方法。

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. 将您的单元标识符命名为"YourcellName" + "Identifier",例如: CustomCellIdentifier 如果您的单元格名称是 CustomCell。

  2. CustomCell.register(for: collectionView)

【讨论】:

    【解决方案4】:

    对于 Swift 4.2 在 viewDidLoad 中

     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 部分中为您的自定义单元格设置标识符。

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多