Custom UiCollectionViewCell class init not being called

回眸只為那壹抹淺笑 提交于 2019-12-24 16:30:10

问题


Hi I'm using this code to try and make the text resize though I can't seen to get the label to resize. Also the init method in the custom class is not being called. Here is my code:

class Cell: UICollectionViewCell {


    @IBOutlet weak var label: UILabel!


    override init(frame: CGRect) {
        super.init(frame: frame)
        print("init—>Not being called???\n")
        self.label.adjustsFontSizeToFitWidth = true
        self.cell.label.sizeToFit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


}

What can I do to get the init to call so. I have also tried adjusting the text in the method

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath

Though the text size of the label is not changing, Here's what the cell looks like with a longs string. Thanks in advance for your help.

If I place -

adjustsFontSizeToFitWidth

or

sizeToFit

:

into ->

 required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.label.adjustsFontSizeToFitWidth = true  // causes error
        self.label.sizeToFit()
    }

I also get an error.


回答1:


Place your code or a breakpoint in init?(coder aDecoder: NSCoder). That should get called if you have your CollectionView added in your storyboard.

Update Handle your IBOutlets as so (in your cell subclass) because in the init function they may not be valid as yet, which I assume is your case:

override func layoutSubviews() 
{
    super.layoutSubviews()
    self.label.adjustsFontSizeToFitWidth = true
    self.label.minimumScaleFactor = 0.8 //set the scale factor or minimumFontSize so that it can then start adjusting the font size.
    Self.label.numberOfLines = 1
}


来源:https://stackoverflow.com/questions/37957262/custom-uicollectionviewcell-class-init-not-being-called

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