在栈视图内创buildUilabels之间的垂直线

我想在代码中创build一个自定义标题的UICollectionView。 因此,我创build了UICollectionViewCell的子类来描述我的自定义标题。 我想在水平线的头部显示五个标签。 所以我创build了五个标签并将它们添加到一个stackView中。 stackview显示我的标签平等填充。 到目前为止一切都完美

标签1标签2标签3标签4标签5

//Label 1 let votesLabel: UILabel = { let label = UILabel() let attributedText = NSMutableAttributedString(string: "Votes", attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12) ]) attributedText.append(NSAttributedString(string: "\n 0", attributes: [NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.systemFont(ofSize: 14)])) label.attributedText = attributedText // label.text = "11\nvotes" label.textAlignment = .center label.numberOfLines = 0 return label }() // label 2 ... 5 // creating the subview and add the labels to my subview addSubview(topDividerView) let stackView = UIStackView(arrangedSubviews: [ votesLabel, and the other 4 labels]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.distribution = .fillEqually addSubview(stackView) // add stackView to my view stackView.topAnchor.constraint(equalTo: topAnchor).isActive = true stackView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true stackView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true stackView.heightAnchor.constraint(equalToConstant: 50).isActive = true 

现在我想在这些标签之间添加单独的竖线:

Label1 | Label2 | Label3 | Label4 | Label5

我创build了一个UIView,但不能在标签之间添加这个视图。 任何人都可以帮助我。 谢谢

如果你在界面生成器中这样做,可以非常容易。 将标签添加到水平堆栈视图,然后在其间添加分隔视图,为分隔视图创build1点宽度约束,将其拥抱优先级设置为高于标签,并将堆叠视图的alignment方式设置为fill和分配到equal spacing 。 而已。 您可能还想要将分频器的宽度约束优先级设置为999,以便xcode在某些情况下不会抱怨破坏约束。

这里是我的快速testing的截图: 在这里输入图像说明

并在模拟器中的结果: 在这里输入图像说明

我的例子是在视图控制器的视图中直接完成的,但是你当然可以用xib文件创build一个新的UIView子类,把标签(和分隔符)放在那里,然后实例化你的视图,如下所示: let myView = Bundle.main.loadNibNamed("MyViewWithLabels", owner: nil, options: nil)![0] as! MyViewWithLabels let myView = Bundle.main.loadNibNamed("MyViewWithLabels", owner: nil, options: nil)![0] as! MyViewWithLabels 。 然后,将您的视图实例添加到您的集合视图cll作为子视图。