lazy var flow:UICollectionViewFlowLayout = {
let f = UICollectionViewFlowLayout.init();
f.estimatedItemSize = CGSize.init(width: 20, height: 60);
f.minimumInteritemSpacing = 10;
f.minimumLineSpacing = 10;
f.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
return f;
}()
import UIKit
class TextLabelCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 5;
self.backgroundColor = DDGlobalNavBarColor();
setUI();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var texts :UILabel = {
let l = UILabel.init();
l.textColor = UIColor.white;
l.backgroundColor = UIColor.clear;
l.textAlignment = .center;
return l;
}()
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let att = super.preferredLayoutAttributesFitting(layoutAttributes);
let string:NSString = texts.text! as NSString
var newFram = string.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: texts.bounds.size.height), options: .usesLineFragmentOrigin, attributes: [
NSAttributedStringKey.font : texts.font
], context: nil)
newFram.size.height += 10;
newFram.size.width += 10;
att.frame = newFram;
// 如果你cell上的子控件不是用约束来创建的,那么这边必须也要去修改cell上控件的frame才行
// self.textLabel.frame = CGRectMake(0, 0, attributes.frame.size.width, 30);
return att;
}
}
extension TextLabelCell{
func setUI() {
self.addSubview(texts);
texts.snp.makeConstraints { (maker) in
maker.left.equalToSuperview().offset(0);
maker.right.equalToSuperview().offset(0);
maker.bottom.equalToSuperview().offset(0);
maker.top.equalToSuperview().offset(0);
// maker.height.equalTo(self.size.height/2);
}
}
}