代码之家  ›  专栏  ›  技术社区  ›  Sener

UiCollectionView单元格动态宽度

  •  1
  • Sener  · 技术社区  · 7 年前

    我有一个 UICollectionView . 如何以编程方式设置单元格宽度=标签宽度

    我已实施 UICollectionViewDelegateFlowLayout UICollectionViewDataSource .

     let musicType = ["Blues", "Klasik Müzik", "Halk Müzikleri", "Hip-hop", "Caz", "Pop", "Rock", " Enstrümantal Müzik", "House", "Rap" , "Slow"]
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return musicType.count
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath as IndexPath) as! CustomCell
            cell.nameLabel.text = musicType[indexPath.item]
            cell.sizeToFit()
            return cell
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            ?????
        }
    
    
    
    }
    
    class CustomCell: UICollectionViewCell {
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupView()
        }
    
        let nameLabel: UILabel = {
           let lbl = UILabel()
            lbl.text = "deneme Tag"
            lbl.translatesAutoresizingMaskIntoConstraints = false
            return lbl
        }()
    
    
        func setupView(){
            backgroundColor = UIColor.red
            addSubview(nameLabel)
            addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[v0]-10-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
            addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    
    
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Josh Homann    7 年前

    您需要获取标签的属性,然后使用给定索引路径的数据创建一个NSAttribute字符串。NSAttributeString有一个size方法,可以告诉您文本应该有多大。

    看起来您的标签没有属性和数据,因此假设您希望单元格为标签的实际大小,且其填充为零:

    let text = NSAttributedString(string: "deneme Tag")
    return text.size()