I want to create a horizontal scrolling stackView of UIViews using .Xib files, So far I've created the .Xib storyboard as well as the cocoaTouch class that goes along with it and am having trouble setting it up since this is my first time working with .Xib files.
I want the output to look something like this:
But when I run the app it throws this error: Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x6000029f13d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key itemImage.'
and I don't know why this is happening since I'm very unfamiliar with .Xib files.
I've set the file owner's class to the WhatsHotTile
class as well as the view itself.
Here is the WhatsHotTile
class:
class WhatsHotTile: UIView {
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemImage: UIImageView!
}
And here is the code where I attempt to create the horizontal scrolling stackView:
for shoe in Shoes {
if shoe.trending == true {
if let whatsHotTile = Bundle.main.loadNibNamed("WhatsHotTile", owner: nil, options: nil)!.first as? WhatsHotTile {
whatsHotTile.itemName.text = shoe.name
whatsHotTile.itemImage.image = shoe.image
whatsHotStackView.addArrangedSubview(whatsHotTile)
}
}
}
One thing that I haven't done that may or may not need to be done is adding a blank UIView within the horizontal stackView that's inside of the the scrollView. Is that something that needs to be done or does doing it completely programatically work?
Since this is my first time working with .Xib files could someone explain why this error is occurring / how to fix it as well as what's the proper way to create .Xib files and use them within your code, if so that would be very much appreciated.
CodePudding user response:
The issue (I believe) is that only some Cocoa Touch classes support .xib files, and UIView
is not one of those. When I opened up Xcode and tried New File -> Cocoa Touch Class -> Subclass of: UIView
, it disabled the checkbox for also create .xib file
. Some example classes that do allow .xib files are the UITableView
and UICollectionView
.
Since you're trying to scroll items horizontally, not vertically, I'd guess you don't want a UITableView
. This leaves the UICollectionView
. This works a lot like the UITableView
, so using what I already knew about table views, plus this Stack Overflow post linked here:
Credit belongs to William T., matt and Ilker Baltaci for the question and answers I referenced to implement the horizontal scrolling functionality.
CodePudding user response:
I recommend using UICollectionView here instead of UIStackView as it supports dynamic data and scrolling by default.