Is it possible to use IBDesignable with UICollectionViewCells and live render them in storyboard?

假如想象 提交于 2019-12-10 13:56:08

问题


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.



来源:https://stackoverflow.com/questions/34692590/is-it-possible-to-use-ibdesignable-with-uicollectionviewcells-and-live-render-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!