Is it possible to use IBDesignable with UICollecti

2019-06-18 16:20发布

问题:

I know how to use @IBDesignable with custom views. but is it possible to use IBDesignable for cells and render them in storyboard?

for example: i have a collectionViewController in storyboard, and added a uiCollectionCell and specified class as my customCellClass.

p.s: i know for using Xibs in collecionViews and tableViews we have to call method registerNib:forReuseIdentifer in code (and i am doing it). just wondered, is it possible to see it's rendered view in storyboard or not.

p.s2: i found this and it works perfectly with UIViews, but don't know how to make it work with CollectionCells and TableCells. :(

回答1:

Yes. Here is what I found with Xcode 10.1 and iOS 12. Adding @IBDesignable to the custom subclass of UICollectionViewCell did work intermittently, but this works more reliably:

  • Add @IBDesignable to a custom subclass of UIView
  • Override layoutSubviews(), and define the appearance there
  • Optionally, if you want to define dummy data for IB only, override prepareForInterfaceBuilder()
  • Add that custom view to your prototype UICollectionViewCell in Interface Builder
  • You should see Interface Builder "build" the views and draw your change in your customer view (I find this unreliable, too. If nothing happens and Menu / Editor / Automatically Refresh Views is checked, make some other change in Interface Builder)

Example Class

@IBDesignable
class Avatar: UIView {

    // Despite not being used for views designed in Interface Builder, must still be defined for custom UIView subclasses with @IBDesignable, or IB will report errors
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    // Used when a view is designed inside a view controller scene in Interface Builder and assigned to this custom UIView subclass
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        self.layer.cornerRadius = self.bounds.width / 2
        self.backgroundColor = UIColor.gray
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        self.backgroundColor = UIColor.blue
    }
}


回答2:

After lots of testing and working with the library I came up with this:

you should not add TableViewCell or CollectionViewCells inside .nib files, instead you have to add simple View. I'm not sure if it's gonna show up inside storyboard or not (haven't checked it yet) but it makes errors go away. Now you can even use autoLayout for self sizing cells.