我将获得字符串数组,这些字符串需要在 swift iOS 中带边框显示。
示例:
let tags = ["Draft", "Sent", "Inbox"]
上面的列表需要转换为扁平字符串并单行显示,如下所示 带有边框草稿图像的预期输出:
Draft Sent Inbox // All tags should have border like below also text colour should be different
我在下面尝试了它的工作原理是制作单行字符串如何为每个字符串创建不同颜色的边框。
func mergeTags(tags: [String]) -> String {
let tagsList : String = tags.reduce("", { $0 == "" ? $1 : $0 + " " + $1 })
return tagsList
}
我认为你应该用标签来做。您可以创建一个像这样的辅助函数,将字符串转换为看起来如上面所示的标签:
func borderedLabel(withText text: String) -> UILabel {
let color = UIColor.blue // or whatever you want
let label = UILabel()
label.textColor = color
label.text = text
label.layer.cornerRadius = 5 // or something
label.layer.borderWidth = 1
label.layer.borderColor = color.cgColor
return label
}
然后您可以在另一个辅助函数中调用它,将它们全部放在一个视图中:
/// Generates a view with bordered labels separated by a given spacing, inline in one row.
func generateBorderedLabelsView(strings: [String], spacing: CGFloat) -> UIView {
let container = UIView()
guard !strings.isEmpty else {
return container
}
let labels = strings.map(borderedLabel(withText:))
var previousLabel: UILabel?
labels.enumerated().forEach { index, label in
container.addSubview(label)
var constraints = [
label.topAnchor.constraint(equalTo: container.topAnchor),
label.bottomAnchor.constraint(equalTo: container.bottomAnchor)
]
if index == 0 {
// if first, anchor leading edge to container view's leading edge
constraints.append(label.leadingAnchor.constraint(equalTo: container.leadingAnchor))
} else if let previousLabel {
// or, anchor leading edge to trailing edge of previous view with the given spacing
constraints.append(label.leadingAnchor.constraint(equalTo: previousLabel.trailingAnchor, constant: spacing))
}
if index == labels.count - 1 {
// if the last label, anchor its trailing edge to the container's trailing edge
constraints.append(label.trailingAnchor.constraint(equalTo: container.trailingAnchor))
}
NSLayoutConstraint.activate(constraints)
previousLabel = label
}
return container
}