我有stackView,其中包含很少的labelViews,每个标签中都写有两个单词。我希望它们在labelView的整个宽度上用省略号分隔。结果是:一个单词靠近左侧,另一个-右侧,并且它们之间有点。注意:如果单词的长度很长,则标签可能占用多行。
编辑
在这里填充我的stackView
for ingredient in ingredients {
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow // just for my needs
textLabel.widthAnchor.constraint(equalToConstant: ingredientsStackView.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text = ingredient.getName() + " " + String(ingredient.getAmount()) + " " + ingredient.getMeasure()
textLabel.textAlignment = .left
textLabel.numberOfLines = 0
textLabel.lineBreakMode = .byWordWrapping
ingredientsStackView.addArrangedSubview(textLabel)
}
ingredientsStackView.translatesAutoresizingMaskIntoConstraints = false
看起来像这样
但是我想要这样的东西
您可以看到ingredientName
和ingredientAmount
之间的点。
我有一个想法可以通过CGFloat
转换here来实现,但是这个问题已经关闭。
一种技术是使用size()
或size()
计算大小,对越来越多的点系列重复该大小,直到达到所需的宽度。
但是,这忽略了第一个示例的微妙(但恕我直言,很重要)方面,即所有行中的点都完美对齐。如果他们不排队,可能会令人分心。
因此,我倾向于定义一个视图来执行此操作,并针对某些共同的祖先视图坐标系执行模量计算。而且,我个人只是将点渲染为boundingRect(with:options:context:)
。
例如:
boundingRect(with:options:context:)
然后,您可以添加两个标签,将椭圆视图的底部与标签的底部基线对齐:
UIBezierPath
产生椭圆,但它们也都完美排列:
class EllipsesView: UIView {
let spacing: CGFloat = 3
let radius: CGFloat = 1.5
var color: UIColor {
UIColor { traitCollection in
switch traitCollection.userInterfaceStyle {
case .dark: return .white
default: return .black
}
}
}
let shapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.strokeColor = UIColor.clear.cgColor
return layer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.fillColor = color.cgColor
let point = convert(bounds.origin, to: window)
let diff = radius * 3 + spacing
let offset = diff - point.x.truncatingRemainder(dividingBy: diff)
let rect = CGRect(x: bounds.minX + offset, y: bounds.maxY - radius * 2, width: bounds.width - offset, height: radius * 2)
let path = UIBezierPath()
var center = CGPoint(x: rect.minX + radius, y: rect.midY)
while center.x + radius < rect.maxX {
path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true)
center.x += diff
}
shapeLayer.path = path.cgPath
}
}
private extension EllipsesView {
func configure() {
layer.addSublayer(shapeLayer)
}
}