iOS - Add vertical line programatically inside a stack view

后端 未结 10 872
悲哀的现实
悲哀的现实 2020-12-25 09:04

I\'m trying to add vertical lines, between labels inside a stack view all programatically.

The desired finish will be something like this image:

I c

10条回答
  •  执念已碎
    2020-12-25 09:39

    @mark-bourke's answer only worked for a single separator. I fixed the invalidateSeparators() method for multiple separators. I haven't tested it with horizontal stack views, but it works for vertical ones:

      private func invalidateSeparators() {
        guard arrangedSubviews.count > 1 else {
          separators.forEach({$0.removeFromSuperview()})
          separators.removeAll()
          return
        }
    
        if separators.count > arrangedSubviews.count {
          separators.removeLast(separators.count - arrangedSubviews.count)
        } else if separators.count < arrangedSubviews.count {
          for _ in 0..<(arrangedSubviews.count - separators.count - 1) {
            separators.append(UIView())
          }
        }
    
        separators.forEach({$0.backgroundColor = self.separatorColor; self.addSubview($0)})
    
        for (index, subview) in arrangedSubviews.enumerated() where arrangedSubviews.count >= index + 2 {
          let nextSubview = arrangedSubviews[index + 1]
          let separator = separators[index]
    
          let origin: CGPoint
          let size: CGSize
    
          if axis == .horizontal {
            let originX = subview.frame.maxX + (nextSubview.frame.minX - subview.frame.maxX) / 2.0 + separatorInsets.left - separatorInsets.right
            origin = CGPoint(x: originX, y: separatorInsets.top)
            let height = frame.height - separatorInsets.bottom - separatorInsets.top
            size = CGSize(width: separatorWidth, height: height)
          } else {
            let originY = subview.frame.maxY + (nextSubview.frame.minY - subview.frame.maxY) / 2.0 + separatorInsets.top - separatorInsets.bottom
            origin = CGPoint(x: separatorInsets.left, y: originY)
            let width = frame.width - separatorInsets.left - separatorInsets.right
            size = CGSize(width: width, height: separatorWidth)
          }
    
          separator.frame = CGRect(origin: origin, size: size)
          separator.isHidden = nextSubview.isHidden
        }
      }
    

提交回复
热议问题