Custom UiCollectionViewCell class init not being c

2019-08-15 07:18发布

问题:

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
}