我想在代码中创建一个自定义标题的UICollectionView。因此,我创建了UICollectionViewCell的一个子类来描述我的自定义头部。我想在我的标题中以一条水平线显示五个标签。因此,我创建了五个标签,并将它们添加到stackView中。堆栈视图显示我的标签被均匀填充。到目前为止,一切都很完美。
Label1 Label2 Label3 Label4 Label5
//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
我创建了一个UIView,但无法在标签之间添加此视图。有人能帮帮我吗?谢谢
发布于 2017-04-24 21:11:27
如果你在界面构建器中做这件事,它可能会非常简单。将标签添加到水平堆叠视图,然后在其中添加分隔视图,为分隔视图创建1点宽度约束,设置它们的拥抱优先级高于标签,并将堆叠视图的对齐方式设置为fill
,分布方式设置为equal spacing
。就这样。您可能还希望将分隔符的宽度约束优先级设置为999,这样xcode在某些情况下就不会因为违反约束而发出警告。
以下是我快速测试的屏幕截图:
以及模拟器中的结果:
我的示例是直接在视图控制器的视图中完成的,但是您当然可以使用xib文件创建一个新的UIView子类,将标签(和分隔符)放在其中,然后实例化如下所示的视图:let myView = Bundle.main.loadNibNamed("MyViewWithLabels", owner: nil, options: nil)![0] as! MyViewWithLabels
。然后,只需将视图实例作为子视图添加到集合视图cll。
https://stackoverflow.com/questions/43596417
复制