swift4.0 collectionViewCell 自適應文字寬度

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);
            
        }
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章