UICollectionView中的UILabel跨两个或多个单元格

时间:2019-04-07 11:50:13

标签: ios swift uicollectionview

我知道如何对一个单元格中的标签进行编程(请参见label2下方),我的问题是,我想建立一个日历,例如,当我有两天的约会时,我需要一个跨越两个单元格的标签(参见图像) ,标签1)知道如何实现吗?每一个帮助都超过了赞赏!

enter image description here

当我使用以下代码时,第二幅图像显示标签被以下单元格隐藏(您可以看到单元格之间的绿色小线):

 let myLabel = UILabel()
    myLabel.clipsToBounds = false
    myLabel.translatesAutoresizingMaskIntoConstraints = false
    cell.addSubview(myLabel)
    myLabel.backgroundColor = UIColor.green
    myLabel.widthAnchor.constraint(equalToConstant: desiredWidth).isActive = true
    myLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
    let margins = cell.layoutMarginsGuide
    myLabel.topAnchor.constraint(equalTo: margins.topAnchor, constant: 15).isActive = true
    myLabel.text = "Appointment"

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,您必须取消选中要绑定到Storyboard中单元的剪辑,或者可以在

中进行操作
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
  // So that the label can go out of bound
  cell?.clipsToBounds = false
  cell?.label.clipsToBounds = false

  .
  .
  .

  return cell
} 

现在,您可以使用带有约束的逻辑在InterfaceBuilder中实现所需的功能

您可以在cellForItemAt中更改Label的框架,类似这样

// Change desiredWidth according to you needs
let desiredWidth = 1000

cell?.wordlabel.frame = CGRect(origin: (cell?.wordlabel.frame.origin)! , size: CGSize(width: desiredWidth, height: 30))

编辑

您可以通过以下方式调整单元格的大小:

extension YourViewController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let font = UIFont.systemFont(ofSize: 13)

    let size = (data[indexPath.row] as NSString).size(withAttributes:[NSAttributedString.Key.font: font])

    // Add your logic here for the desired cell width
    let additionalpadding: CGFloat = 1000
    return CGSize(width: size.width + additionalpadding, height: 30)
}

}