Как загрузить пользовательскую ячейку (xib) в ячейке UICollectionView с помощью быстрой
Я создал небольшой пример проекта с использованием Swift. Я создал "MyCustomView" в виде xib, который содержит метку, кнопку и изображение, как показано в приведенном ниже коде:
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 для справки. ![Screenshot]()
В StoryBoard → ViewController добавлена UIViewCollection, которая, как показано на рисунке ниже. В этой коллекции я хочу, чтобы эта оранжевая ячейка содержала мой пользовательский xib для загрузки во время выполнения.
Как мне этого добиться?
![enter image description here]()
Новый модифицированный код, предложенный 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 import 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
MyCustomView, чтобы они были подклассом UICollectionViewCell, а не UIView.
-
Удалить override init(frame: CGRect)
, required init?(coder aDecoder: NSCoder)
, func xibSetup()
, func loadViewFromNib() → UIView
из MyCustomView
-
Я серьезно не мог понять, как вы используете свой установщик и получатель для mytitleLabelText и myCustomImage. Если это бесполезно, избавьтесь от него.
-
Наконец, у вас останется только IBOutlets в MyCustomView.
-
Для лучшей практики кодирования измените имя с MyCustomView на MyCustomCell (необязательно)
-
Перейдите к xib, выберите xib и установите его класс MyCustomView.
![enter image description here]()
- На этом же экране смените владельца файла на свой контроллер хостинга ViewView.
![enter image description here]()
- В ViewDidLoad вашего viewController зарегистрируйте свой кончик.
self.collectionView.registerNib(UINib(nibName: "your_xib_name", bundle: nil), forCellWithReuseIdentifier: "your_reusable_identifier")
- В cellForItemAtIndexPath,
let cell : MyCustomView = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) as! MyCustomView
cell.lblName.text = "bla bla" //access your Cell IBOutlets
return cell
- Наконец, чтобы контролировать размер ячейки, либо переопределите делегат collectionView, либо просто перейдите к своему collectionView, выберите в нем collectionCell и перетащите его в соответствии с вашим измерением :) Вот и все :)
Удачного кодирования. Ищите учебники для лучшего понимания. Не могу объяснить всем делегатам, так как я закончу писать здесь.
Удачного кодирования
Ответ 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)
}
}
Шаги о том, как использовать
-
Назовите свой идентификатор ячейки как "YourcellName" + "Identifier"
например: CustomCellIdentifier
если ваше имя ячейки CustomCell.
-
CustomCell.register(for: collectionView)
Ответ 4
Для Swift 4.2 в viewDidLoad
self.collectionView.register(UINib(nibName: "your_xib_name", bundle: nil), forCellWithReuseIdentifier: "your_reusable_identifier")
в cellForItemAt indexPath:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "your_reusable_identifier", for: indexPath) as! MyCustomView
И, конечно, как сказал @Raj Aryan: не забудьте установить идентификатор для вашей пользовательской ячейки в разделе xib.